我试图使用json-lib jar解析一个简单的json数据 . JSON数据格式如下:

{"plantDetails":
    [{
        "common":"New Plant 1",
            "botanical":"",
            "light":"Mostly Shady",
            "price":0,
            "availDate":"10/25/2012",
            "indoor":false,
            "id":null
    },{
        "common":"New Plant 1",
            "botanical":"",
            "light":"Mostly Shady",
            "price":0,
            "availDate":"10/25/2012",
            "indoor":false,
            "id":null
    },{
        "common":"New Plant 1",
            "botanical":"",
            "light":"Mostly Shady",
            "price":0,
            "availDate":"10/25/2012",
            "indoor":false,
            "id":null
    }]
}

为此,我使用以下代码:

try {
    net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(jb.toString());               
    JSONArray arr = jsonObject.getJSONArray("plantDetails");
    //net.sf.json.JSONObject jsonObject1 = jsonObject.getJSONObject("plantDetails");
    Iterator iter = arr.iterator();
    while (iter.hasNext()) {
        JSONObject object = (JSONObject) iter.next();
        System.out.println(object.getString("common"));
        System.out.println(object.getString("botanical"));
    }
} catch (Exception e) {
    // crash and burn
    System.out.println(e.getMessage());
}
} catch (Exception e) {
    e.printStackTrace();
}

当有多个JSONObject(即我的情况下为3)时,此代码可以正常工作 . 但不幸的是,当JSON对象的数量只有1时,它不起作用 . 它抛出异常: net.sf.json.JSONException: JSONObject["plantDetails"] is not a JSONArray.

如何检查是否存在多个JSONObject?

解决此问题的一种方法是,一旦在try / catch块中仅针对一个JSONObject抛出上述异常,然后获取相应的值,就使用这段代码:

net.sf.json.JSONObject jsonObject1 = jsonObject.getJSONObject("plantDetails");

但我不想这样:

1)可能有一些更好的方法来实现相同而不是捕获异常并处理它以获取Object值

2)需要知道实现相同的最佳方式

请让我知道这件事 .

问候,