测试它是JSONObject还是JSONArray [英] Test if it is JSONObject or JSONArray

查看:117
本文介绍了测试它是JSONObject还是JSONArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json流,可以是:

I have a json stream which can be something like :

{"intervention":

    { 
      "id":"3",
              "subject":"dddd",
              "details":"dddd",
              "beginDate":"2012-03-08T00:00:00+01:00",
              "endDate":"2012-03-18T00:00:00+01:00",
              "campus":
                       { 
                         "id":"2",
                         "name":"paris"
                       }
    }
}

或类似的东西

{"intervention":
            [{
              "id":"1",
              "subject":"android",
              "details":"test",
              "beginDate":"2012-03-26T00:00:00+02:00",
              "endDate":"2012-04-09T00:00:00+02:00",
              "campus":{
                        "id":"1",
                        "name":"lille"
                       }
            },

    {
     "id":"2",
             "subject":"lozlzozlo",
             "details":"xxx",
             "beginDate":"2012-03-14T00:00:00+01:00",
             "endDate":"2012-03-18T00:00:00+01:00",
             "campus":{
                       "id":"1",
                       "name":"lille"
                      }
            }]
}   

在我的Java代码中,我执行以下操作:

In my Java code I do the following:

JSONObject json = RestManager.getJSONfromURL(myuri); // retrieve the entire json stream     
JSONArray  interventionJsonArray = json.getJSONArray("intervention");

在第一种情况下,上述方法不起作用,因为流中只有一个元素。 。
如何检查流是对象还是数组

In the first case, the above doesn't work because there is only one element in the stream.. How do I check if the stream is an object or an array ?

我试过 json.length()但它没有用..

I tried with json.length() but it didn't work..

谢谢

推荐答案

这样的事情应该这样做:

Something like this should do it:

JSONObject json;
Object     intervention;
JSONArray  interventionJsonArray;
JSONObject interventionObject;

json = RestManager.getJSONfromURL(myuri); // retrieve the entire json stream     
Object intervention = json.get("intervention");
if (intervention instanceof JSONArray) {
    // It's an array
    interventionJsonArray = (JSONArray)intervention;
}
else if (intervention instanceof JSONObject) {
    // It's an object
    interventionObject = (JSONObject)intervention;
}
else {
    // It's something else, like a string or number
}

这样做的好处是只需从主 JSONObject 获取属性值一次。由于获取属性值涉及遍历哈希树或类似物,这对性能有用(对于它的价值)。

This has the advantage of getting the property value from the main JSONObject just once. Since getting the property value involves walking a hash tree or similar, that's useful for performance (for what it's worth).

这篇关于测试它是JSONObject还是JSONArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆