我有这个JSON字符串:
String json = "{"countries":{"2":"China","3":"Russia ","4":"USA"},"capitals":{"2":Beijing,"4":null,"3":Moscow}}";
我将string转换为HashMap,使用如下:
HashMap<String,Object> map = new Gson().fromJson(json, new TypeToken<HashMap<String, Object>>(){}.getType());
System.out.println(map.get("countries")+"@@@@@"+map.get("capitals"));
现在输出是:
{2=China, 3=Russia , 4=USA}@@@@@{2=Beijing, 4=null, 3=Moscow}
我想用数字连接这些值。我想创建两个这样的数组列表:
)——(中国、俄罗斯、美国)
B) -(北京、莫斯科、零)
我该怎么做呢?
首先,你需要将map.get("label")
转换为LinkedTreeMap<Integer, String>
,然后用它的值创建新的ArrayList
String json = "{"countries":{"2":"China","3":"Russia ","4":"USA"},"capitals":{"2":Beijing,"4":null,"3":Moscow}}";
HashMap<String,TreeMap<Integer, String>> map = new Gson().fromJson(json, new TypeToken<HashMap<String, TreeMap<Integer, String>>>(){}.getType());
ArrayList<String> countries = new ArrayList<>(map.get("countries").values());
System.out.println(countries);
ArrayList<String> capitals = new ArrayList<>(map.get("capitals").values());
System.out.println(capitals);
您可以遍历国家键集以填充大写数组:
List<String> countries = new ArrayList<>(countriesMap.values());
List<String> capitals = new ArrayList<>();
for (String countryKey : countriesMap.keySet()) {
capitals.add(capitalsMap.get(countryKey));
}