How do I parse this JSON in Java? - java

I'm a bit new to this and it's doing my head in! I keep getting this error:
Error parsing data org.json.JSONException: No value for tname
This is the json:
[{"tname":"2"},{"kword":"||ice+skating+rink"}]
And here is my java code:
String result = response.toString();
try
{
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag", ", type: " + json_data.getString("tname")+
", keyword: " + json_data.getString("kword"));
type += json_data.getString("tname");
keyword += json_data.getString("kword");
}
Any help greatly appreciated.

Your second object doesn't have tname. you should check and see if the object has a property before accessing it
if(json_data.has("tname"))
type += json_data.getString("tname");
if(json_data.has("kword"))
keyword += json_data.getString("kword");

Related

I am not able to get the data from a Json array

Error message: com.example.myjson W/System.err: org.json.JSONException: Value
of type org.json.JSONObject cannot be converted to JSONArray
JSON is as follows
{
"temp":296.88,
"feels_like":298.86,
"temp_min":296.88,
"temp_max":296.88,
"pressure":1013,
"humidity":89,
"sea_level":1013,
"grnd_level":986
}
I could get data from this alone
String weatherInfo = jsonObject.getString("weather");
Not from this string Why ?
JSONArray jsonArray1 = new JSONArray(weatherInfo1);
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String weatherInfo = jsonObject.getString("weather");
String weatherInfo1 = jsonObject.getString("main");
Log.i("weatherMainContent", weatherInfo1);
Log.i("Weather Details" , weatherInfo);
JSONArray jsonArray = new JSONArray(weatherInfo);
JSONArray jsonArray1 = new JSONArray(weatherInfo1);
Log.i("full " , jsonArray1.toString());
String message = "";
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String main = jsonObject1.getString("main");
String description = jsonObject1.getString("description");
Log.i("Weather side Details" , weatherInfo);
Log.i("temperaturerrr", jsonObject1.getString("temp_min"));
String temp_min = jsonObject1.getString("temp_min");
Log.i("temperature", jsonObject1.getString("temp_min"));
String pressure = jsonObject1.getString("pressure");
if (!main.equals("") && !description.equals("") && !temp_min.equals("")) {
message += main + ":" + description +";" + temp_min + "\r\n";
} else {
Toast.makeText(getApplicationContext(), "couldn't find the giberish you mentioned :(", Toast.LENGTH_SHORT).show();
}
Log.i("Main", jsonObject1.getString("main"));
Log.i("Description", jsonObject1.getString("temp_min"));
}
if (!message.equals("")) {
resultTextView.setText(message);
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "couldn't find the giberish you mentioned :(", Toast.LENGTH_SHORT).show();
}
}
}
Your Json is not an Array, but an Object.
Create a new JSONObject of your Json String.
Then just use the object and use the getDouble("propertyName") method to get the value of the property:
String json = "{\"temp\":296.88,\"feels_like\":298.86,\"temp_min\":296.88,\"temp_max\":296.88,\"pressure\":1013,\"humidity\":89,\"sea_level\":1013,\"grnd_level\":986}";
JSONObject weatherInfo = new JSONObject(json);
double temp = weatherInfo.getDouble("temp");
double feels_like = weatherInfo.getDouble("feels_like");
double temp_min = weatherInfo.getDouble("temp_min");
double temp_max = weatherInfo.getDouble("temp_max");
double pressure = weatherInfo.getDouble("pressure");
double humidity = weatherInfo.getDouble("humidity");
double sea_level = weatherInfo.getDouble("sea_level");
double grnd_level = weatherInfo.getDouble("grnd_level");
System.out.println(temp);
System.out.println(feels_like);
System.out.println(temp_min);
System.out.println(temp_max);
System.out.println(pressure);
System.out.println(humidity);
System.out.println(sea_level);
System.out.println(grnd_level);
If this is your data
"{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80},"clouds":{"all":90},"dt":1485789600,"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},"id":2643743,"name":"London","cod":200} "
you have to just make some changes in the code to retrieve
String jsonString = "your string";
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONArray("weather");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject weatherObj = jsonArray.getJSONObject(i);
System.out.println(weatherObj);
}
String baseValue = json.getString("base");
Object mainValue = json.get("main");
Object visibilityValue = json.get("visibility");
Object windValue = json.get("wind");
#shivas To retrieve the below json { "main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80} from the source json, kindly check first which property is JSONArray and JSONObject.
Here is the code to retrieve it.
main,wind are JSONObject and weather is a JSONArray.
So assuming sourcejson is the entire JSONObject,
JSONObject main = sourcejson.optJSONObject("main");
System.out.println(main.toString());
JSONObject wind = sourcejson.optJSONObject("wind");
System.out.println(wind.toString());
JSONArray weather = sourcejson.optJSONArray("weather");
for (int i = 0; i < weather.length(); i++) {
JSONObject weatherObj = weather.getJSONObject(i);
System.out.println(weatherObj.toString());
}
String base = sourcejson.optString("base");
int visibility = sourcejson.optInt("visibility");
Try this, you will get your data.

How to send an JSON array to another method

I am fetching an JSON response from an API.
I should return those JSON response to another method with selected fields
Here I am fetching all the JSON response and putting it to an JSONArray which I should return to another method.
How to fetch both String and Long returning fields and put it into an JSON array and return it to another method
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("/2.0/clusters/list");
request.addHeader("Authorization", "bearerToken");
request.addHeader("cache-control", "no-cache");
HttpResponse response = client.execute(request);
System.out.println("Response Code:" +
response.getStatusLine().getStatusCode());
String json = EntityUtils.toString(response.getEntity());
System.out.println("Gather Details\n");
JSONObject cluster = new JSONObject(json);
JSONArray clusterJsonArray = cluster.getJSONArray("clusters");
for (int i = 0; i < clusterJsonArray.length(); i++) {
JSONObject iteratingObj = array.getJSONObject(i);
String id = iteratingObj.get("id").toString();
String time = iteratingObj.get("time").toString();
System.out.println("Id:" + id + "time:" + time + "\n");
List<String> strList = new ArrayList<>();
for (int p = 0; p < clusterJsonArray.length(); p++) {
strList.add(clusterJsonArray.getJSONObject(p).getString("id"));
strList.add(clusterJsonArray.getJSONObject(p).getString("time"));
}
System.out.println("Arr:" + strList);
if (response.getStatusLine().getStatusCode() != 200) {
System.out.println("Failed HTTPresponse" + response.getStatusLine().getStatusCode() + "" + json);
}
}
Help me out to send the response with selected fields to other method in which that JSONarray should take both String and Long values and store it in one varible of JSONArray.
Here is the incoming JSON:
"clusters": [
{ "id": "0411-0089ki", "driver": { }, "start_timestamp": 1568952332573, },
Here JSONObject["time"] not a string is the error i am facing when i am putting it to JSONArray
The intention of the above code you mentioned is not clear. But,
Here JSONObject["time"] not a string is the error i am facing when i
am putting it to JSONArray
You can use:
long time = iteratingObj.getLong("start_timestamp");
But you do not use the local variables of id and time in anywhere.
I think the logic is incorrect in the code that you put in the question. Please double check the logic for these 2 loops.
for (int i = 0; i < clusterJsonArray.length(); i++) {
for (int p = 0; p < clusterJsonArray.length(); p++) {

Writing into JSONArray

I'm reading JSON file, taking out the values and doing some changes.
Basically I added some values to array. After that I want to write it back on a file. When I write JSONArray back to file is written as string and not JSONArray object. How can I write it well?
In the following code I'm writing into JSON file:
JSONArray rooms = (JSONArray) jsonObject.get("rooms");
for (int i = 0; i < rooms.size(); i++) {
JSONObject room = (JSONObject) rooms.get(i);
String roomName = (String) room.get("roomName");
System.out.println("RoomName: " + roomName + " Size: " + "O: " + oldRoomListSize.get(roomName) + " N: " + roomList.get(roomName).getRoomBook().size());
if(oldRoomListSize.get(roomName) < roomList.get(roomName).getRoomBook().size()) {
int n = roomList.get(roomName).getRoomBook().size() - oldRoomListSize.get(roomName);
for (int j = n; j > 0; j--) {
int lenght = roomList.get(roomName).getRoomBook().size();
JSONArray schedule = (JSONArray) room.get("schedule");
Reservation r = roomList.get(roomName).getRoomBook().get(lenght-j);
schedule.add(r);
}
}
}
fileWriter.write(jsonObject.toJSONString());
fileWriter.close();
As you can see, is being written as string and it bring me problems when I want to read it back.
"schedule":["{Day: 1 - Start Time: 10}"]
File Reader:
JSONArray schedule = (JSONArray) room.get("schedule");
for (int j = 0; j < schedule.size(); j++) {
JSONObject s = (JSONObject) schedule.get(j);
String day = (String) s.get("day");
String startTime = (String) s.get("startTime");
lRoom.setRoomBook(Integer.parseInt(day), Integer.parseInt(startTime));
}
Error: java.lang.ClassCastException: java.lang.String cannot be cast
to org.json.simple.JSONObject
Error occurs, after enter new value to array (Introduced day and start time). It's writen as string, and when i try to read it again, give me a error saying i cant parse it since there's a string on array.
Input file:
{
"rooms":[
{"maxOccupants":"10",
"schedule":[{"startTime":"1","day":"10"},{"startTime":"20","day":"20"},{"startTime":"11","day":"122017"}],
"tv":"false",
"mobilePhone":"false",
"projector":"true",
"buildID":"1",
"floor":"2",
"roomName":"room1"},
{"maxOccupants":"4",
"schedule":[{"startTime":"10","day":"1"},{"startTime":"11","day":"122017"},{"startTime":"11","day":"15"}],
"tv":"false",
"mobilePhone":"false",
"projector":"false",
"buildID":"1",
"floor":"2",
"roomName":"room2"},
{"maxOccupants":"5",
"schedule":[{"startTime":"1","day":"10"},{"startTime":"11","day":"122017"}],
"tv":"false",
"mobilePhone":"false",
"projector":"true",
"buildID":"2",
"floor":"3",
"roomName":"room3"}
]
}
Problem solved! I was not creating a JSONObject, so I was introducing a directly object to JSON Array and it forced conversation to String.
Here is the resolution of the problem:
JSONObject jsonObj = new JSONObject();
String startTime = String.valueOf(r.getStartTime());
String day = String.valueOf(r.getDay());
jsonObj.put("startTime", startTime);
jsonObj.put("day", day);
schedule.add(jsonObj);

at 0 of type java.lang.String cannot be converted to JSONArray

I am facing this exception at 0 of type java.lang.String cannot be converted to JSONArray don't know why? i have use this before in different work didn't get this exception
List<NameValuePair> pair = new ArrayList<>();
pair.add(new BasicNameValuePair("id", String.valueOf(getitemno)));
json = JSONParser.makeHttpRequest("http://192.168.1.51:80/StopViewApi/index.php","POST",pair);
Log.d("Route Response", json.toString());
int success = 0;
try {
success = json.getInt(TAG_SUCCESS);
Routearrray = new ArrayList<String>();
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (success == 1) {
JSONArray jsonarray;
json = new JSONObject(JSONParser.Result);
JSONArray jArray = json.getJSONArray("data");
for (int i = 0; i <= jArray.length(); i++) {
jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);
Counter++;
if (Counter <=jArray.length()) {
//Routearrray.add(Stopnames);
Log.d("Stop name:", Stopnames);
//Log.d("Route name:", Routearrray.toString());
} else {
break;
}
}
JSON URL
{
"data":[
"Rawat","Islamabad Mor","Kaak Pull","Lohi Bher","Koral Chowk","Gangal",
"Khana Bridge","Zia Masjid","Kuri Road","Dhok Kala Khan","Faizabad",
"Pirwadhai Mor","Tanki Stop I-8\/4","I-8\/3 Stop","Al Shifa Hospital","AIOU",
"Zero Point","Children Hospital","F-8\/4","Ali Hospital"
],
"success":1,
"status":200,
"status_message":"Login Successfull"
}
Error: at Line
jsonarray = jArray.getJSONArray(i);
From your JSON, jArray is a array of String and not an array of JSONArray.
Replace:
jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);
with:
Stopnames = jArray.getString(i);
the for loop should be
for (int i = 0; i < jArray.length(); i++) {
You're trying to parse String values as JSONArray. jArray is an array of Strings, not JSONArrays, so all you need to do is just extract the String values from it.
JSONArray jArray = json.getJSONArray("data");
// You already have a JSONArray, now all you need to do is extract String values from it
for (int i = 0; i <= jArray.length(); i++) {
Log.d("Stopnames: " , jArray.getString(i));
....
}
Thats because you "data" is of type json array. whats inside "data" is not a jsonarray, they are just jsonstrings.
change the following lines
jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);
to
stopnames += jArray.getString(i);
You are trying to get jsonarray from jsonarray, while the json array contains json objects. try this
JSONObject jsonObject = jsonArray.getJSONObject(i)
Stopnames = jsonObject.getString(Integer.toString(i))

Get JSON String in java with org.json

[{"post":{"titel":"Glee","interpret":"Bran Van 3000","jahr":"1997","id":"5"}},{"post":{"titel":"Goodbye Country (Hello Nightclub)","interpret":"Groove Armada","jahr":"2001","id":"4"}},{"post":{"titel":"Beauty","interpret":"Ryuichi Sakamoto","jahr":"1990","id":"1"}}]
The above string is what i have in json and now what i want to do is to just get the values of "post" and "titel" as in the above string what i am having 3 values of post which makes sense to me. But, now what i want is to print all the 3 values of post and each value in the post string.
JSONArray jsonArray = new JSONArray(jsonString);
columns = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
columns[i]=jsonObject.getString("post");
}
above code returns me 3 values of post. WHat i can do if i want to print values of post and the each value of column in post?
I would do something like this (I don't use the columns array just to print, and this code is not tested):
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject postObj = jsonObject.getJSONObject("post");
for (String i : postObj.keys()) {
System.out.println("Key: " + i + "; Value: " + postObj.getString(i));
}
}
That is, process each element of the Object returned by the "post" object of each array element.

Categories