How to check whether the given object is object or Array in JSON string

为君一笑 提交于 2019-11-26 22:54:16

问题


I am getting JSON string from website. I have data which looks like this (JSON Array)

 myconf= {URL:[blah,blah]}

but some times this data can be (JSON object)

 myconf= {URL:{try}}

also it can be empty

 myconf= {}    

I want to do different operations when its object and different when its an array. Till now in my code I was trying to consider only arrays so I am getting following exception. But I am not able to check for objects or arrays.

I am getting following exception

    org.json.JSONException: JSONObject["URL"] is not a JSONArray.

Can anyone suggest how it can be fixed. Here I know that objects and arrays are the instances of the JSON object. But I couldn't find a function with which I can check whether the given instance is a array or object.

I have tried using this if condition but with no success

if ( myconf.length() == 0 ||myconf.has("URL")!=true||myconf.getJSONArray("URL").length()==0)

回答1:


JSON objects and arrays are instances of JSONObject and JSONArray, respectively. Add to that the fact that JSONObject has a get method that will return you an object you can check the type of yourself without worrying about ClassCastExceptions, and there ya go.

if (!json.isNull("URL"))
{
    // Note, not `getJSONArray` or any of that.
    // This will give us whatever's at "URL", regardless of its type.
    Object item = json.get("URL"); 

    // `instanceof` tells us whether the object can be cast to a specific type
    if (item instanceof JSONArray)
    {
        // it's an array
        JSONArray urlArray = (JSONArray) item;
        // do all kinds of JSONArray'ish things with urlArray
    }
    else
    {
        // if you know it's either an array or an object, then it's an object
        JSONObject urlObject = (JSONObject) item;
        // do objecty stuff with urlObject
    }
}
else
{
    // URL is null/undefined
    // oh noes
}



回答2:


Quite a few ways.

This one is less recommended if you are concerned with system resource issues / misuse of using Java exceptions to determine an array or object.

try{
 // codes to get JSON object
} catch (JSONException e){
 // codes to get JSON array
}

Or

This is recommended.

if (json instanceof Array) {
    // get JSON array
} else {
    // get JSON object
}



回答3:


I was also having the same problem. Though, I've fixed in an easy way.

My json was like below:

[{"id":5,"excerpt":"excerpt here"}, {"id":6,"excerpt":"another excerpt"}]

Sometimes, I got response like:

{"id":7, "excerpt":"excerpt here"}

I was also getting error like you. First I had to be sure if it's JSONObject or JSONArray.

JSON arrays are covered by [] and objects are with {}

So, I've added this code

if (response.startsWith("[")) {
  //JSON Array
} else {
  //JSON Object 
}

That worked for me and I wish it'll be also helpful for you because it's just an easy method

See more about String.startsWith here - https://www.w3schools.com/java/ref_string_startswith.asp




回答4:


Using @Chao answer i can solve my problem. Other way also we can check this.

This is my Json response

{
  "message": "Club Details.",
  "data": {
    "main": [
      {
        "id": "47",
        "name": "Pizza",

      }
    ],

    "description": "description not found",
    "open_timings": "timings not found",
    "services": [
      {
        "id": "1",
        "name": "Free Parking",
        "icon": "http:\/\/hoppyclub.com\/uploads\/services\/ic_free_parking.png"
      } 
    ]
  }
}

Now you can check like this that which object is JSONObject or JSONArray in response.

String response = "above is my reponse";

    if (response != null && constant.isJSONValid(response))
    {
        JSONObject jsonObject = new JSONObject(response);

        JSONObject dataJson = jsonObject.getJSONObject("data");

        Object description = dataJson.get("description");

        if (description instanceof String)
        {
            Log.e(TAG, "Description is JSONObject...........");
        }
        else
        {
            Log.e(TAG, "Description is JSONArray...........");
        }
    }

This is used for check that received json is valid or not

public boolean isJSONValid(String test) {
        try {
            new JSONObject(test);
        } catch (JSONException ex) {
            // e.g. in case JSONArray is valid as well...
            try {
                new JSONArray(test);
            } catch (JSONException ex1) {
                return false;
            }
        }
        return true;
    }


来源:https://stackoverflow.com/questions/9817315/how-to-check-whether-the-given-object-is-object-or-array-in-json-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!