java - 测试是 JSONObject 还是 JSONArray

我有一个 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/

相关文章:

javascript - JSON.stringify 深层对象

java - 如何防止 Map 中的空值和 bean 中的空字段通过 Jackson 序列化

sql - 如何查询空对象的 json 列?

java - Spring MVC + JSON = 406 Not Acceptable

android - Kotlin:遍历 JSONArray

javascript - ngRepeat 按深度属性过滤

c# - 如何在 C# 中将 `+` 添加到属性名称?

python - 无返回时处理 JSON 解码错误

c# - 将 JSON 字符串解析为对象的最简单的 C# 函数是什么?

java - 将 JSONArray 转换为字符串数组