简体   繁体   中英

Android: Fetch the very first value in JSON data using Retrofit Library

I am using the Retrofit Library in Android to read the JSON data. I want to only read the country names from the below JSON ie just the value. Is it possible to read such JSON data using Retrofit Library?

{
    "China": ["Guangzhou", "Fuzhou", "Beijing"],
    "Japan": ["Tokyo", "Hiroshima", "Saitama", "Nihon'odori"],
    "Thailand": ["Bangkok", "Chumphon", "Kathu", "Phang Khon"],
    "United States": ["Mukilteo", "Fairfield", "Chicago", "Hernando", "Irving", "Baltimore", "Kingston"],
    "India": ["Bhandup", "Mumbai", "Visakhapatnam"],
    "Malaysia": ["Pantai", "Kuala Lumpur", "Petaling Jaya", "Shah Alam"]
}
List<String> list = new ArrayList<>();
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
    String key = iter.next();
    list.add(key); 
    try {
        Object value = json.get(key);
    } catch (JSONException e) {
        // Something went wrong!
    }
}
   Log.d("TAG",list.toString());

for example :

public class Country{
    private List<String> name;

}

An associative array translates to a Map in Java:

Map<String, Country > countries = new Gson().fromJson(json, new TypeToken<Map<String, Country >>(){}.getType());

in retrofit just add to model class:

@Expose
 private Map<String, Country> result;

You can use HashMap<String,ArrayList<String>> as retrofit result obj and get the keys.

or just get it with string then cast it to hasmap

 val typeToken: Type = object : TypeToken<HashMap<String, ArrayList<String>>>()
        {}.type
 val result = Gson().fromJson<HashMap<String, ArrayList<String>>>(tmp, typeToken)

then you can iterate trough the keys.

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