org.json.JSONException: "JSON object not found in JSON array" - java

A very simple JSON like this (response.getBody().toString()):
{"per_page":50,"total":93,"last_page":2,"stars":[]}
Has some problems when I want to parse it:
JSONObject object = new JSONObject(response.getBody()); // no error
System.out.println(object.getJSONObject("total")); // not found
org.json.JSONException: JSONObject["total"] not found.
Other properties cannot be parsed either:
JSONArray startups = object.getJSONArray("stars");
org.json.JSONException: JSONObject["stars"] not found.
The key is to hold the value of response.getBody()
String json = response.getBody().toString();

Inside object total is not JSONObject it is an Int value, that's why you code crashing.
So use this
System.out.println(String.valueOf(object.getInt("total")));
instead of
System.out.println(object.getJSONObject("total"));

String json = "{\"per_page\":50,\"total\":93,\"last_page\":2,\"stars\":[]}":
JSONObject jsonObject = new JSONObject (json);
JSONArray jsonArray = jsonObect.getJSONArray("stars");
int perPage = jsonObject.getInt("per_page");
try like this...

In addition to earlier answer, to parse array, use getJSONArray as
JSONArray ja = jsonObj.getJSONArray("stars");
You can loop-over the array as:
for(int j=0; j<ja.length(); j++) {
JSONObject json = ja.getJSONObject(j);
// do same as before for string, int or other data types
}

Related

Read out nested JSONObject with Java. Don't get the inner JSONObject

I'm trying to read a JSONObject from within another JSONObject. The first output works, the second, i.e. the JSONObject within, does not. Here I get the following error
org.json.JSONException: JSONObject["Values"] not found.
This is the output of the first object / array
ergebnis: {"Description":"","Objects":[{"RefStr":"76-1044-0","ClassName":"Application","Values":{"providerorg-refstr":"262-462-0",...}]}
This is how I try to get the data:
JSONObject jsonObject = new JSONObject(ergebnis);
System.out.println(jsonObject);
JSONObject inside = jsonObject.getJSONObject("Values");
System.out.println(inside);
Values object is present in Objects. This objects is an array. You can try like below,
JSONObject jsonObject = new JSONObject(json);
System.out.println(jsonObject);
JSONObject jsonObject1= jsonObject.getJSONObject("ergebnis");
System.out.println(jsonObject1);
JSONArray objects = jsonObject1.getJSONArray("Objects");
System.out.println(objects);
JSONObject inside = objects.getJSONObject(0).getJSONObject("Values");
System.out.println(inside);

Json array inside array retrieve values Android

i m trying to get values from JSONArray inside array, i m able to retrieve whole JSON values into JSONArray successfully but not able to retrieve values inside JSONArray. When i convert JSONArray to JSONObject to get values stored inside JSONArray. It gives error: org.json.JSONException: No value for "banner"
Here is JSON code, i verified JSON code with jsonlint.com and it showed JSON is Validate,
[
{"code":"banner","moduletitle":0,
"banner":
[
{"image":"http://imageurl"},
{"image":"http://imageurl"},
{"image":"http://imageurl"}
]
}
]
I m trying to get this from 3 hour but no luck. i m new in JSON and do not know how JSON Actually work, and also read abut GSON Library to get JSON values. here is My Java code.
JSONArray jsonObj = null;
String image_url = "";
String banner_code ="";
try {
jsonObj =new JSONArray(lib_function.getJSONUrl( jsontags.Top_Banner_JOSN_URLs));
Log.d("value retrun :","" +jsonObj);
//---vlaue is coming and print in Log ----//
} catch (JSONException e) {
Log.v("Error in Parser :", " " + e);
Log.d("no value retrun :", "failed to convert");
}
try{
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// populate the array
jo.put("arrayName", jsonObj);
JSONArray subArray = jo.getJSONArray("banner");
image_url= subArray.getString(Integer.parseInt("image"));
Log.d("banner code",""+subArray);
}catch(Exception e)
{
Log.d("not working",""+e);
}
I folllow this question but luck:
How to parse JSON Array inside another JSON Array in Android
If anyone suggest, what i m doing wrong will be appreciate. or let me know, where i can get more information about json
UPDATE thanks too all to give their precious time for answering my stupid question. All answers are correct , but i can accept only one answer. A Big thanks to all
Here:
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// populate the array
jo.put("arrayName", jsonObj);
Because parsing jsonObj JSONArray so no need to create new JSONArray and JSONObject to extract it from jsonObj. remove all above three lines.
banner JSONArray is inside JSONObject which is contained by jsonObj JSONArray, get it as:
JSONObject jsonObject=jsonObj.optJSONObject(0);
JSONArray subArray = jsonObject.getJSONArray("banner");
// get code key from `jsonObject`
String strCode=jsonObject.optString("code");
// get all images urls from `subArray`
for(int index=0;index<subArray.length();index++){
JSONObject imgJSONObject=subArray.optJSONObject(index);
// get image urls
String strImgURL=imgJSONObject.optString("image");
}
Also, if jsonObj JSONArray contains multiple JSONObject's then use for-loop to iterate it.
I am assuming you have the rest of the values accessible to you, so posting just this snippet.
code=jsonObject.getString("code");
moduletitle=jsonObject.getString("moduletitle");
banner=jsonObject.getJSONArray("banner");
jsonObj =new JSONArray(lib_function.getJSONUrl( jsontags.Top_Banner_JOSN_URLs);
From above line you will get JSONArray. So now loop it and get you banner JSONArray.Again loop bannerArray and you will get image Urls
If You want value of "image" which is in json arrray than
String response = "your response";
try{
JsonArray jAry = new JsonArray(response);
JsonObject jObj = jAry.getJsonObject(0);
JsonArray jsonBanner = jObj.getJsonArray("banner");
JsonObject temp;
for(int i=0;i<jsonBanner.length;i++){
temp = jsonBanner.getJsonObject(i);
String image = temp.optString("image");
}
}

Issue With JSON Object in Java?

I have a JSON Object which converted into String and saved into database .But when i am trying to get it back it is throwing exception.My object is something like that...
{"COLUMN":["Type","Sub Type","F.P.","P.P.","Process","Due To Start"]}
How can we get the data back in Normal form?
My Java Code is.....
JSONObject obj = new JSONObject();
JSONArray the_json_array = obj.getJSONArray(userReorderOption);
int size = the_json_array.size();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
arrays.add(another_json_object);
}
And Exception i am getting....
net.sf.json.JSONException: JSONObject["{\"TASKLIST_COLUMN_REORDER\":[\"Type\",\"Sub Type\",\"F.P.\",\"P.P.\",\"Process\",\"Due To Start\"]}"] is not a JSONArray.
And this is java Code how i am creating JSON Object and saving into database...
String userReorderSelection;
Set set = new LinkedHashSet(userReorderSelection);
JSONObject json = new JSONObject();
json.accumulate("COLUMN", set);
saveJSONObj("PrimaryKeyColumn", json.toString());
Thanks Tichodroma,
But as i told i am using net.sf.json.JSONObject class and above things we can achieve from this class too..What i did to solve the above issue?...Please have a look on the Java code...
JSONObject jsonObj = new JSONObject();
JSONObject obj = jsonObj.fromObject(userReorderOption);
JSONArray columnName = (JSONArray) obj.get("COLUMN");
for (int i = 0; i < columnName.size(); i++) {
System.out.println(columnName.getString(i));
}
This code work fine for me with my Json Jar**(net.sf.json)**
Your JSON is not a JSONArray.
A JSONArray is an ordered sequence of values.
You have a JSONObject.
A JSONObject is an unordered collection of name/value pairs.
Edit:
Using the JSON implementation from org.codehaus.jettison.json, you can do this:
String json = "{\"COLUMN\":[\"Type\",\"Sub Type\",\"F.P.\",\"P.P.\",\"Process\",\"Due To Start\"]}";
JSONObject obj = new JSONObject(json);
JSONArray column = (JSONArray) obj.get("COLUMN");
for (int i = 0; i < column.length(); i++) {
final String field = column.getString(i);
System.out.println(field);
}
Result:
Type
Sub Type
F.P.
P.P.
Process
Due To Start

Android: JSONObject cannot be converted to JSONArray

I want to get data from php file to Android using JSON. This is my code:
....
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
When I debug the program there is JSONException on this line:
JSONObject last = timeline.getJSONObject(0);
Data is {"a":1,"b":2,"c":3,"d":4,"e":5} and the Exception is:
org.json.JSONException: Value {"d":4,"e":5,"b":2,"c":3,"a":1} of type org.json.JSONObject cannot be converted to JSONArray
The exception message is quite explicit and a look at the JSON syntax diagrams should be illustrative. The JSON string that your code received is:
{"a":1,"b":2,"c":3,"d":4,"e":5}
This string represents an object, not an array. An example of an array would be this:
[1, 2, 3, 4, 5]
or even this:
[{"a":1,"b":2,"c":3,"d":4,"e":5}]
Note that starting and closing brackets.
I think that you will find that the exception location is slightly misleading. I don't know if it is a result of some sort of lazy initialization or something else, but I believe that the cause is actually this line:
JSONArray timeline = new JSONArray(data);
Since the data string represents a JSON object and not an array, this operation is clearly impossible.
In Json arrays are described using [].
There you define an object with five attributes.
JSONArray timeline = new JSONArray(data);
// change JSONArray to JSONObject
JSONObject timeline = new JSONObject(data);// Like This
Your JSON data is not an array.
Your json response is in Object form, not in Array form.So you have to simply parse your json object. Suppose "data" is the JSONObject tag in response.
Following is the way of Parsing:
HttpEntity e = r.getEntity();
String result = EntityUtils.toString(e);
JSONObject response=new JSOBObject(result);
JSONOBject Data=response.getJSONObject("data");
int a=Data.getInt("a");
int b=Data.getInt("b");
int c=Data.getInt("c");
int d=Data.getInt("d");
int e=Data.getInt("e");
Thanks.

converting from String to JSONArray or JSONObject in Java

I'm trying to use the JSON library to consume twitter information from the get search feature. I'm getting the error:
A JSONArray text must start with '[' at 1 [character 2 line 1]
So it's basically in the wrong form. Some people are saying this needs to be an object but everytime I call the constructor it says that it can't take a String as input. How do I get this string into the form of a JSONArray so that I can access it's elements.
Here is my code:
URL twitterSource = new URL("http://search.twitter.com/search.json?q=google");
ByteArrayOutputStream urlOutputStream = new ByteArrayOutputStream();
IOUtils.copy(twitterSource.openStream(), urlOutputStream);
String urlContents = urlOutputStream.toString();
// parse JSON
System.out.println(urlContents);
JSONArray jsonArray = new JSONArray(urlContents);
// use
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println(jsonObject.getString("id"));
System.out.println(jsonObject.getString("text"));
System.out.println(jsonObject.getString("created_at"));
}
my print statement shows the string contains:
{"completed_in":0.318,"max_id":144850937012428800,"max_id_str":"144850937012428800","next_page":"?page=2.....................
This is a string in the form of a JSON object but it is not actually an object. It's still a string. I'm printing a String. HOw can I get this into an Object or better yet a JSONArray so that I can actually access its elements.
That's a JSON object, not an array.

Categories