我有一个 JSONObject
{"2016":{"12":{"20":{"19":{"DonationTime":11111111111,"Donation":10}}}}}
我想用每个键将其转换为新 map
int i = 0;
for (Iterator<String> keysItr = object.keySet().iterator(); keysItr.`hasNext(); i++) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
map.put(key, value);
}
}
SOP(map); //but here i want to get 4 maps
}
我想要 4 张 map ,例如
hourMap[19] = "{"DonationTime":11111111111,"Donation":10}";
dayMap[20] = "{"19":{"DonationTime":11111111111,"Donation":10}}";
monthMap[12] = "{"12":{"20":{"19":{"DonationTime":11111111111,"Donation":10}}}";
yearMap[2016] = "{"12":{"20":{"19":{"DonationTime":11111111111,"Donation":10}}}";
我正在使用 for 循环,但无法获得 i 的增量值。
最佳答案
你可以简单地将 JSON 对象转换为 map ,然后从那里你可以轻松地取出你感兴趣的四个 map
这是一个简单的例子
(注意下面在大 JSON 图上的代码可能会导致一些问题,因为它是基于递归的转换)
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
public class JsonMapConverter {
public static void main(String... x) throws Exception {
String jsonString = "{\"2016\":{\"12\":{\"20\":{\"19\":{\"DonationTime\":11111111111,\"Donation\":10}}}}}";
JSONObject json = new JSONObject(jsonString);
Map<String,Object> yearMap = toMap(json);
String year = yearMap.keySet().iterator().next();
Map<String,Object> monthMap = ((Map<String, Object>) yearMap.get(year));
String month = monthMap.keySet().iterator().next();
Map<String,Object> dayMap = (Map<String, Object>) monthMap.get(month);
String day = dayMap.keySet().iterator().next();
Map<String,Object> hourMap = (Map<String, Object>) dayMap.get(day);
System.out.println(yearMap);
System.out.println(monthMap);
System.out.println(dayMap);
System.out.println(hourMap);
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
对于 JSON 到映射的转换,我使用此答案中的代码 ( Convert a JSON String to a HashMap )
代码是根据json字符串编写的,如果json中存在多个年月日,您可以根据自己的需要调整代码
关于java - 如何使用迭代器 java 将 JSONObject 转换为新 Map 的所有键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41243880/