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

后端 未结 4 1778
不思量自难忘°
不思量自难忘° 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: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
    }
    

提交回复
热议问题