如何从JSONObject Java获取子属性

时间:2017-06-20 04:38:22

标签: java arrays json

我的代码中有一个问题,我需要从JSONObject打印子属性。实际上,由于某些目的,我希望在JSONArray中拥有属性值。

< - 到目前为止,我做了 - >

String preStringSingle = responseSingle.body().string(); // has the JSONObject
JSONObject resultsJObject = new JSONObject(preStringSingle);
JSONArray resultsJArray1 = resultsJObject.optJSONArray("data");
System.out.println(resultsJArray1);

< - 的JSONObject - >

 "status": true,
"locale": "en-US",
"error_code": null,
"message": "OK",
"data": [
    {
        "service_list_access_mode": 0,
        "service_list_domain": "http://www.hotsalesmarket.com",
        "service_list_auth_method": 0,
        "service_list_auth_user": null,
        "service_list_auth_password": null,
        "http_method": "GET",
        "map_service_lists": [
            {
                "path": "sdfm.assets/assets/cameras/5799.jpg",
                "service_item_id": 5799
            },
            {
                "path": "dsf.assets/assets/cameras/5798.jpg",
                "service_item_id": 5798
            },
            {
                "path": "sdfsdf.assets/assets/cameras/6701.jpg",
                "service_item_id": 6701
            }
        ]
    }
],
"timestamp": "2017-06-20T03:46:38Z"
}

我想获取子属性“map_service_lists”中的所有详细信息。

< - 所需输出 - >

{
    "path": "sdfsdf.assets/assets/cameras/5799.jpg",
                "service_item_id": 5799
},
{
    "path": "/sdfsdfs.assets/assets/cameras/5798.jpg",
                "service_item_id": 5798
},
{
    "path": "/sdfsdf.assets/assets/cameras/6701.jpg",
                "service_item_id": 6701
}

2 个答案:

答案 0 :(得分:1)

你必须像你一样继续,但在层次结构中增加一级:

JSONArray data        = resultsJObject.optJSONArray("data");
JSONObject firstData  = data.optJSONObject(0);
JSONArray services    = firstData.optJSONArray("map_service_lists");

System.out.println(services);

(如果您不想要,请从结果中删除数组括号。)

答案 1 :(得分:0)

String preStringSingle = responseSingle.body().string();
JSONObject resultsJObject = new JSONObject(preStringSingle);
JSONArray resultsJArray1 = resultsJObject.optJSONArray("data");
JSONObject j = new JSONObject(resultsJArray1.get(0).toString());
JSONArray resultsJArray2 = j.optJSONArray("map_service_lists");
System.out.println(resultsJArray2);