简体   繁体   中英

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.

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();
}

try using TypeToken.

Gson gson = new Gson();

List<Country> list = gson.fromJson(gson.toJson(what_you_get_data), new TypeToken<ArrayList<Country>>(){}.getType()); //Country is VO class what you make.

Here, you can see that your data looks like HashMap , so I just tried in that way and your data parsed successfully without a glitch:

  1. Create Pojo's:

     public class Countries { private HashMap<String, Country> countries; public HashMap<String, Country> getCountries() { return countries; } public void setCountries(HashMap<String, Country> countries) { this.countries = countries; } } public class Country { private String name; private String nameTurkish; private String nameNative; public String getName() { return name; } public void setName(String name) { this.name = name;} public String getNameTurkish() { return nameTurkish; } public void setNameTurkish(String nameTurkish) { this.nameTurkish = nameTurkish; } public String getNameNative() { return nameNative; } public void setNameNative(String nameNative) { this.nameNative = nameNative; } }
  2. Create a Gson Object and parse it:

     Gson gson = new Gson(); // Countries Object Type testC = new TypeToken<Countries>(){}.getType(); Countries ob = gson.fromJson(test, testC); String newData = gson.toJson(ob.getCountries()); System.out.println("New Data: "+newData); // All country in HashMap Type country = new TypeToken<HashMap<String, Country>>(){}.getType(); HashMap<String, Country> countryHashMap = gson.fromJson(newData, country); // Print All HashMap Country for (Map.Entry<String, Country> set: countryHashMap.entrySet()) { System.out.println("==> "+set.getKey() + " = " + set.getValue()); }
  3. Output:

     I/System.out: ==> 1 = Country{name='Cyprus', nameTurkish='KKTC', nameNative='Kıbrıs'} I/System.out: ==> 2 = Country{name='Turkey', nameTurkish='Türkiye', nameNative='Türkiye'} I/System.out: ==> 3 = Country{name='Monaco', nameTurkish='Monako', nameNative='Monaco'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM