3

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.

Ahmet B.
  • 1,290
  • 10
  • 20
  • get all keys from countries json object and use for loop to get and save name of each country in list. – satuser Jun 10 '20 at 04:12

3 Answers3

2

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();
}
Zain
  • 37,492
  • 7
  • 60
  • 84
  • hello, 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 – Ahmet B. Jun 10 '20 at 04:25
  • @Ahmet thanks for notifying this, I have modified the answer with `UPDATE` section, and it worked for your given JSON.. hope it can help – Zain Jun 10 '20 at 05:10
  • thank you @Zain , your edited model works well when I put the data into Asset folder. However my JSON data is in API and I want to get it using retrofit, can you give me an advice? – Ahmet B. Jun 10 '20 at 05:25
  • @Ahmet you're most welcome .. please have look at [the answer here](https://stackoverflow.com/questions/40973633/retrofit-2-get-json-from-response-body/40973772), and especially the online tool that will help you automatically create your pojo & retrofit classes – Zain Jun 10 '20 at 05:31
0

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.
S T
  • 1,068
  • 2
  • 8
  • 16
0

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'}
    
double-beep
  • 5,031
  • 17
  • 33
  • 41
  • I already have looked at it. There is a constant "content" object, but in my example every country has its own SerializedName – Ahmet B. Jun 10 '20 at 04:29