有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓 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。 多谢各位


共 (2) 个答案

  1. # 1 楼答案

    我想你应该用这样的东西

    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();
            }
    
  2. # 2 楼答案

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

    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