Exception while parsing JSON data - java

I am parsing JSON data from this link:
http://twyst.in/api/v1/near/30/30
As the data is too large, I am posting only the (problem) relevant data here:
{
"info": "[{\"outlet\":{\"__v\":1,\"_id\":\"5316d59326b019ee59000026\",\"photos\":[],\"twyst_meta\":{\"recommend_list\":[],\"reviews\":[]},\"outlet_meta\":{\"links\":[],\"status\":\"active\",\"accounts\":[\"531574eeae738d654c00000a\",\"535a1a1e827651ca03000122\"]},\"attributes\":{\"dine_in\":true,\"outdoor\":true,\"air_conditioning\":\"Not Available\",\"parking\":\"Available\",\"reservation\":\"Not Required\",\"wifi\":\"Not Available\",\"tags\":[\"Pizza\",\"Pasta\",\"Italian\",\"Galleria\",\"DLF Phase 4\"],\"payment_options\":[\"cash\",\"amex\",\"visa\",\"master\"],\"cuisines\":[\"Italian\",\"Pizza\",\"Gelato\"],\"timings\":\"11 AM - 11 PM\",\"cost_for_two\":{\"min\":3,\"max\":4}},\"links\":{\"other_urls\":[],\"youtube_url\":\"\",\"twitter_url\":\"\",\"facebook_url\":\"https://www.facebook.com/pages/Crusty-gourmet-pizza-more/390843954384130\",\"website_url\":\"\"},\"contact\":{\"emails\":{\"email\":\"bob_nugent56#yahoo.com\",\"person\":\"\"},\"phones\":{\"number\":\"\",\"landline\":\"02355156616\",\"reg_mobile\":[{\"_id\":\"4639320000e4532779b17de7\",\"num\":\"9134000410\"}
This is not the end of JSON data, it goes on...
But when the following line of code is executed, I am getting a JSONException. The e.printStackTrace() method tells me that there is typeMismatch error.
JSONObject object = new JSONObject(str); //1
JSONArray array = object.getJSONArray("info"); //2
I have tried replacing the line 2 with the following code:
JSONObject newObject = object.getJSONObject("info");
But here also I encountered the same problem.
I have checked the complete data, it is correct, no syntax error.
Can anybody help me with the issue ? Can the presence of double quotes before starting of JSONArray be the root of this problem ?
Thanks.

info is not an array or an object. It's a string, which just happens to contain the JSON-encoded representation of another array. You will have to get that string and run it through a second JSON decoding pass:
JSONArray array = new JSONArray(object.getString("info"));

JSONObject json;
Object info;
JSONArray infoJsonArray;
JSONObject infoObject;
json = new JSONObject(str);
Object info= json.get("info");
if (info instanceof JSONArray) {
// It's an array
infoJsonArray = (JSONArray)info;
}
else if (info instanceof JSONObject) {
// It's an object
infoObject = (JSONObject)info;
} else {
// It's something else, like a string or number
}

Related

how to check what return type is of object in jsonobject

In my code I my a call to a service. from the returned json object I am interested in an object. this object is a json array. sometimes, depending on the provided info in the submit this json array object is empty or does not exist.
How can I check if the object in the json object is of type jsonarray before I create an object out from it?
JSONObject VODB = (JSONObject) JSONreturnObj.get("VODB");
if (null != VODB.get("KNDV430")){
if (VODB.getJSONArray("KNDV430") instanceof JSONArray){
JSONArray KNDV430 = VODB.getJSONArray("KNDV430");
customer.setCustResp((String) ((JSONObject)KNDV430.get(0)).get("responsible"));
}
}
now I get a message in my server log:
org.json.JSONException: JSONObject["KNDV430"] is not a JSONArray.
which I want to avoid.
How should I adapt my code?
Replace
if (VODB.getJSONArray("KNDV430") instanceof JSONArray)
with
if (VODB.get("KNDV430") instanceof JSONArray)
You're getting that error from the first getJSONArray in the condition of the if. So this should work:
JSONObject VODB = (JSONObject) JSONreturnObj.get("VODB");
if (null != VODB.get("KNDV430")){
if (VODB.get("KNDV430") instanceof JSONArray){
JSONArray KNDV430 = VODB.getJSONArray("KNDV430");
...
}
}
You can view the source code of the method JSONObject.getJSONArray().

Java read Json array in Json object

I have a String like this:
{"api_authentication":{"api_response":{"token":"XXXXXXXXXXXXXXXXXXXXXXXXX","firstname":"John","disabled":false,"attempts":0,"id":123,"lastname":"Malkovitch","expire":false,"status":0}}}
I can turn this string into an object:
JSONObject jobj = new JSONObject(response);
But I don't find how to get the token value, I tried creating JSONArrays but i get a not found exception.
You can do it like this ;
final JSONObject api_authentication = jobj.getJSONObject("api_authentication");
final JSONObject api_response = api_authentication.getJSONObject("api_response");
System.out.println(api_response.getString("token"));
if JSON any value in curlybrackets { ... } , this is jsonObject . If values are in [ ... ], this is JsonArray. Also you can get which one is object or array, and get it relevant fields from this. So all of json elements are with curly bracket in your problem. Get it as JsonObject.
this might work by the look of what you have posted. The posted code snippet shows that it is a single JSON object and not a JSONArray.
Hence try the following:
JSONObject jobj = new JSONObject(response);
String newtoken = jobj.getJSONObject("api_authentication").getJSONObject("api_response").getString("token"); //declare the variable `newtoken` somhwere before of a desired type
You could try something like:
Object tokenValue = jobj.getJSONObject("api_authentication").getJSONObject("api_response").get("token");
After that you can cast the object to the desired type or use something like getString(.) straightaway.

Check json array has any item

My program is to get a list of Java objects from the "result" string derived from the AsyncTask. In order to do so, I need to use JsonParser to get an JsonArray. In case the "result" string is [], the JsonArray is also []. How can I detect if there is any item in this Json array. I've tried all of suggestions, even detected at the "result" string, nothing is working for me, could you please help? My JsonArray: []
try{
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(orderList).getAsJsonArray();
System.out.println("Inside fromJasonToJava, array: " + array); //This prints out array: []
lst = new ArrayList<Order>();
if(array.get(0)!= null) { //It goes wrong here, I need a working "if" condition
//Value is not null
for (final JsonElement json : array) {
JSONObject jsonObject = new JSONObject(String.valueOf(json));
System.out.println("Inside fromJasonToJava, jsonObject:" + jsonObject);
}
}
}catch(Exception e){
throw new Exception("Convert json to java error [fromJasonToJava()]", e);
}
Inside your if check for size instead, if you are using org.json.simple.JSONArray
if(array.size() != 0)
or if you using org.json.JSONArray
if(array.length() != 0)
You may use if(array.length() > 0)
You no need to use the if condition as java's for-each is smart enough to handle this.
If the array doesn't have any vale or it's empty then it will not get executed at all.
So use this code:
for (final JsonElement json : array) { // it will not get executed at all if array is empty
JSONObject jsonObject = new JSONObject(String.valueOf(json));
System.out.println("Inside fromJasonToJava, jsonObject:" + jsonObject);
Instead of
if(array.get(0)!= null) { //It goes wrong here, I need a working "if" condition
//Value is not null
for (final JsonElement json : array) {
JSONObject jsonObject = new JSONObject(String.valueOf(json));
System.out.println("Inside fromJasonToJava, jsonObject:" + jsonObject);
}

How do I detect if an embedded JSON element is a JSONObject or JSONArray in Java

I am receiving json and am trying to operate on it using the JSONObject and JSONArray classes. I have nested objects and need to determine if those nested objects are arrays or objects. The problem is that if I assume it is an object and it is actually an array, when I get call getJSONObject, an exception is raised. I'm wondering if the only way to do this is just to add try/catch blocks or if there is a better way to do this. For example, say I have:
{"key1": "val1",
"key2": {"level2": {"level3": "val3"}}
}
I may also have the level2 element with multiple values and coming in as an array:
{"key1": "val1",
"key2": {"level2": [{"level3": "val3"}]}
}
How would I extract the level2 object (as an object) and determine if it is an object or an array? Is the only way to really do this using string manipulation?
If I do something like:
jsonObj.getJSONObject("key2").getJSONObject("level2");
It will result in an error: "org.json.JSONException: JSONObject["level2"] is not a JSONObject and conversly, if I call getJSONArray("level2") and level2 is not an array I will get an error indicating it is not an array.
You can use optJSONObject() & optJSONArray() methods to check if the underlying is an Object or Array. Below is an example for that.
JSONObject json = new JSONObject("{\"key1\": \"val1\",\n" +
" \"key2\": {\"level2\": {\"level3\": \"val3\"}}\n" +
"}");
JSONObject json1 = new JSONObject("{\"key1\": \"val1\",\n" +
" \"key2\": {\"level2\": [{\"level3\": \"val3\"}]}\n" +
"}");
if(json.getJSONObject("key2").optJSONObject("level2") != null) {
System.out.println("json : it is a jsonobject");
}
else if(json.getJSONObject("key2").optJSONArray("level2") != null) {
System.out.println("json : it is a jsonarray");
}
if(json1.getJSONObject("key2").optJSONObject("level2") != null) {
System.out.println("json1 : it is a jsonobject");
}
else if(json1.getJSONObject("key2").optJSONArray("level2") != null) {
System.out.println("json1 : it is a jsonarray");
}
Use 'jsonObj.get("level2)' and check whether the type is JsonArray and then try to cast it.
If you're open to using Jackson's Databind module, it's pretty straightforward:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
// ...
// parse your JSON data into a JsonNode
JsonNode jsonObj = new ObjectMapper().readTree(yourJsonString);
// should really do some error checking here unless you're 100% sure
// you're always going to be getting "key2" and "level2" in your JSON
// data structure; look into Jackson's "hasNonNull()" function
JsonNode level2 = jsonObj.get("key2").get("level2");
if (level2.isArray()) {
ArrayNode level2arr = (ArrayNode)level2;
// ... do something with level2arr as an array
// ...
} else if (level2.isObject()) {
// ... use it as an object node
// ...
}
I would stringify the JSON object and check the index of '{' or '['.
Given a Json, I would stringify it. And if the index of '{' is 0 in the stringified object then its a Json Object and if the index of '[' is 0 in the stringified object then its a Json Array.
I use Vertx framework and I can verify them as follows:
JsonObject jsonObject = new JsonObject().put("name", "avishek");
JsonArray jsonArray = new JsonArray().add("Vizury").add("MediaIQ");
System.out.println(jsonObject.toString().indexOf("{") == 0); //Json Object
System.out.println(jsonArray.toString().indexOf("[") == 0); //Json Array

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.

Categories