我正在使用Android中的Retrofit
库来阅读JSON
数据。
我只想从下面JSON
读取国家名称,即只读取值。是否可以使用JSON
库阅读此类Retrofit
数据?
{
"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"]
}
答案 0 :(得分:1)
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());
答案 1 :(得分:0)
例如:
public class Country{
private List<String> name;
}
关联数组转换为Java中的Map:
Map<String, Country > countries = new Gson().fromJson(json, new TypeToken<Map<String, Country >>(){}.getType());
在改造中只需添加到模型类:
@Expose
private Map<String, Country> result;
答案 2 :(得分:0)
您可以使用HashMap<String,ArrayList<String>>
作为改造结果obj并获取密钥。
或者只是用字符串获取它然后将其转换为hasmap
val typeToken: Type = object : TypeToken<HashMap<String, ArrayList<String>>>()
{}.type
val result = Gson().fromJson<HashMap<String, ArrayList<String>>>(tmp, typeToken)
然后你可以通过键迭代。