且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-29 09:16:58

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

JSON objects and arrays are instances of JSONObject and JSONArray, respectively. Add to that the fact that JSONObject has a get method that will return you an object you can check the type of yourself without worrying about ClassCastExceptions, and there ya go.

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
}