Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Java check element is a JSONArray or JSONObject

Tags:

How to check whether an element is a JSONArray or JSONObject. I wrote the code to check,

if(jsonObject.getJSONObject("Category").getClass().isArray()) {

} else {

}

In this case if the element 'category' is JSONObject then it work fine but if it contains an array then it throw exception: JSONArray cannot be converted to JSONObject. Please help. Thanks.

like image 637
Neetesh Avatar asked Sep 02 '11 14:09

Neetesh


People also ask

How do you check if it is a JSONArray or JSON object in Java?

JSONArray interventions; if(intervention == null) interventions=jsonObject. optJSONArray("intervention"); This will return you an array if it's a valid JSONArray or else it will give null .

How do I check if an object is JSON object?

To check if JavaScript object is JSON, we can use the JSON. parse method. const isJson = (data) => { try { const testIfJson = JSON. parse(data); if (typeof testIfJson === "object") { return true; } else { return false; } } catch { return false; } };


3 Answers

Yes, this is because the getJSONObject("category") will try to convert that String to a JSONObject what which will throw a JSONException. You should do the following:

Check if that object is a JSONObject by using:

   JSONObject category=jsonObject.optJSONObject("Category");

which will return a JSONObject or null if the category object is not a json object. Then you do the following:

   JSONArray categories;
   if(category == null)
        categories=jsonObject.optJSONArray("Category");

which will return your JSONArray or null if it is not a valid JSONArray .

like image 91
Ovidiu Latcu Avatar answered Oct 23 '22 05:10

Ovidiu Latcu


Even though you have got your answer, but still it can help other users...

 if (Law.get("LawSet") instanceof JSONObject)
 {
    JSONObject Lawset = Law.getJSONObject("LawSet");                        
 }
 else if (Law.get("LawSet") instanceof JSONArray)
{
    JSONArray Lawset = Law.getJSONArray("LawSet");
}

Here Law is other JSONObject and LawSet is the key which you want to find as JSONObject or JSONArray.

like image 32
Vikas Gupta Avatar answered Oct 23 '22 04:10

Vikas Gupta


String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
  //you have an object
else if (json instanceof JSONArray)
  //you have an array

tokenizer is able to return more types: http://developer.android.com/reference/org/json/JSONTokener.html#nextValue()

like image 20
neworld Avatar answered Oct 23 '22 06:10

neworld