如何检查给定对象是JSON字符串中的对象还是数组

时间:2012-03-22 06:13:28

标签: java getjson json

我从网站获取JSON字符串。我有这样的数据(JSON数组)

 myconf= {URL:[blah,blah]}

但有时这些数据可以是(JSON对象)

 myconf= {URL:{try}}

也可以是空的

 myconf= {}    

我希望在它的对象时执行不同的操作,而在它的数组时则不同。直到我的代码,我试图只考虑数组,所以我得到以下异常。但我无法检查对象或数组。

我遇到了异常

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

任何人都可以建议如何修复它。在这里,我知道对象和数组是JSON对象的实例。但我找不到一个函数,我可以用它来检查给定的实例是数组还是对象。

我已尝试使用此if条件但没有成功

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

5 个答案:

答案 0 :(得分:32)

JSON对象和数组分别是JSONObjectJSONArray的实例。除此之外,JSONObject有一个get方法可以返回一个对象,你可以检查自己的类型,而不必担心ClassCastExceptions,而且还有。

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
}

答案 1 :(得分:7)

有很多方法。

如果您担心系统资源问题/滥用Java异常来确定数组或对象,则不建议使用此方法。

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

或者

建议这样做。

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

答案 2 :(得分:1)

我也有同样的问题。虽然,我已经很容易解决了。

我的json如下所示:

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

有时候,我得到的反应如下:

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

我也像你一样得到了错误。首先,我必须确定它是JSONObject还是JSONArray

  

JSON数组由[]覆盖,对象使用{}

所以,我已添加此代码

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

这对我有用,我希望它对你也有帮助,因为它只是一个简单的方法

答案 3 :(得分:0)

使用@Chao回答我可以解决我的问题。其他方式我们也可以检查一下。

这是我的Json回复

{
  "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"
      } 
    ]
  }
}

现在您可以像这样检查哪个对象是JSONObjectJSONArray 作为回应。

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...........");
        }
    }

这用于收到json有效的检查

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;
    }

答案 4 :(得分:0)

以下使用 jackson api 的示例代码可用于始终获取 json 字符串作为 java 列表。 适用于数组 json 字符串和单个对象 json 字符串。

导入 com.fasterxml.jackson.databind.ObjectMapper;

public class JsonDataHandler {
    public List<MyBeanClass> createJsonObjectList(String jsonString) throws JsonMappingException, JsonProcessingException {
        ObjectMapper objMapper = new ObjectMapper();
        objMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        List<MyBeanClass> jsonObjectList = objMapper.readValue(jsonString, new TypeReference<List<MyBeanClass>>(){});
        return jsonObjectList;
    }
}
相关问题