Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a child attribute from JSONObject Java

Tags:

java

json

arrays

I have a problem in my code where I need to print a child attribute from a JSONObject. Actually, I want to have the attribute values in a JSONArray because of some purposes.

<--So far I did-->

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"
}

I wanted to get all the details in the child attribute "map_service_lists".

<--Desired output-->

{
    "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
}
like image 727
Mohammed Shereif Avatar asked Feb 05 '26 03:02

Mohammed Shereif


1 Answers

You just have to continue like you did, but additional level down the hierarchy:

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

System.out.println(services);

(Remove the array brackets from the result if you don't want them).

like image 61
SHG Avatar answered Feb 07 '26 17:02

SHG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!