我有一个 json 流,它可以是:
{"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 代码中,我执行以下操作:
JSONObject json = RestManager.getJSONfromURL(myuri); // retrieve the entire json stream
JSONArray interventionJsonArray = json.getJSONArray("intervention");
在第一种情况下,上述方法不起作用,因为流中只有一个元素..
如何检查流是 object
还是 array
?
我用 json.length()
试过,但没用..
谢谢
最佳答案
应该这样做:
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
获取属性值一次。由于获取属性值涉及遍历哈希树或类似的,这对性能很有用(对于它的值(value))。
https://stackoverflow.com/questions/9988287/