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

后端 未结 4 1771
不思量自难忘°
不思量自难忘° 2020-12-05 08:04

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 c

相关标签:
4条回答
  • 2020-12-05 08:37

    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;
        }
    
    0 讨论(0)
  • 2020-12-05 08:40

    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
    }
    
    0 讨论(0)
  • 2020-12-05 08:57

    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

    0 讨论(0)
  • 2020-12-05 08:59

    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
    }
    
    0 讨论(0)
提交回复
热议问题