java中Json类中的get和getJSONObject有什么区别?



JsonFormat:

{
    "product": [{
        "description": "my describtion",
        "isStock": "instock",
        "linkArray": [{
            "link": "http://rozinleather.ir/demo/wp-content/uploads/2016/05/8e4996-1.jpg"
        }, {
            "link": "http://rozinleather.ir/demo/wp-content/uploads/2016/05/19b37f-1.jpg"
        }, {
            "link": "http://rozinleather.ir/demo/wp-content/uploads/2016/05/33bc31-1.jpg"
        }, {
            "link": "http://rozinleather.ir/demo/wp-content/uploads/2016/05/459e33-1.jpg"
        }, {
            "link": "http://rozinleather.ir/demo/wp-content/uploads/2016/05/a18f87-1.jpg"
        }, {
            "link": "http://rozinleather.ir/demo/wp-content/uploads/2016/05/c58d16-1.jpg"
        }, {
            "link": "http://rozinleather.ir/demo/wp-content/uploads/2016/05/d952f8-2.jpg"
        }]
    }],
    "success": 1
}

我不明白如何得到嵌套的JsonObject。谢谢你。

首先,您需要创建一个传递JSON字符串作为参数的JSONObject:

JSONObject jsonObject = new JSONObject(jsonString);

然后,根据您的需要,您可能想要获取一个数组,另一个JSON对象或JSONObject的值:

JSONArray productArray = jsonObject.getJSONArray("product");
Integer success = jsonObject.getInt("success");

你可以遍历JSONArray并获得数组的所有元素,并对数组的每个对象(提取值,获取元素的数组或对象等)做你想做的事情:

for (int i = 0; i < productArray.length(); i++) {
    JSONObject product = productArray.getJSONObject(i);
    String description = product.getString("description");
    ...
}

了解JSONObjectJSONArray可用方法:

JSONObject

JSONArray

我觉得你应该这样写

try {
            JSONObject root = new JSONObject("yourJsonString");
            JSONArray products = root.getJSONArray("product");
            for (int i = 0; i < products.length(); ++i){
                JSONObject prod = products.getJSONObject(i);
               // now parse product
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

最新更新