我有一个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");
在第一种情况下,上述方法不起作用,因为流中只有一个元素。如何检查流是an object还是an array?
object
array
我尝试过,json.length()但是没有用。
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只需从一次获取属性值。由于获取属性值涉及遍历哈希树或类似的树,因此对于性能(价值而言)很有用。
JSONObject