Reputation: 177
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
i.e 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"]
}
Upvotes: 1
Views: 557
Reputation: 568
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;
Upvotes: 0
Reputation: 494
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.
Upvotes: 0
Reputation: 3339
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());
Upvotes: 1