Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from nested JSON objects using Gson

I would like get countynames from the API and it returns nested objects;

"countries": {
    "1": {
        "name": "Cyprus",
        "nameTurkish": "KKTC",
        "nameNative": "Kıbrıs"
    },
    "2": {
        "name": "Turkey",
        "nameTurkish": "Türkiye",
        "nameNative": "Türkiye"
    },
    "3": {
        "name": "Monaco",
        "nameTurkish": "Monako",
        "nameNative": "Monaco"
    },

and so on there are more than 200 countries and every county has its own "NUMBER_ID". In the end I want to list all "name" information. I think I should use JsonDeserializer but unfortunately I couldn't.

like image 214
Ahmet B. Avatar asked Sep 13 '26 08:09

Ahmet B.


1 Answers

The entire JSON response can be read as a JSONObject that has multiple elements in it that you can iterate through and get different data.

String jsonResponse = ""; // Put the entire JSON response as a String 
JSONObject root = new JSONObject(jsonResponse);

JSONArray rootArray = root.getJSONArray("countries"); // root element of the json respons

for (int i = 0; i < rootArray.length(); i++) {

    JSONObject number = rootArray.getJSONObject(i);
    String country = number.getString("name"); // Get country name

    // Here you can add `country` into a List
}

UPDATE:

but there is no array in my JSON file, all of them are objects, every country is in an object and every object has its own SerializedName

You can read it into JSONOjbect, and instead of using a JSONArray, you can iterate over the length of the JSONObject as below.

try {
    JSONObject root = new JSONObject(jsonResponse);
    JSONObject countries = root.getJSONObject("countries");

    for (int i = 1; i <= countries.length(); i++) {

        JSONObject number = countries.getJSONObject(String.valueOf(i));
        String country = number.getString("name"); // Get country name

        // Here you can add the `country` into a List
    }

} catch (JSONException e) {
    e.printStackTrace();
}
like image 126
Zain Avatar answered Sep 14 '26 21:09

Zain



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!