如何使用iterator java将JSONObject转换为其所有键的新Map

我有一个JSONObject

{"2016":{"12":{"20":{"19":{"DonationTime":11111111111,"Donation":10}}}}} 

我想用每个键将它转换为新地图

 int i = 0; for (Iterator 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张地图

 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对象转换为地图,然后从那里你可以轻松地取出你感兴趣的四个地图

这是一个简单的例子

(在大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 yearMap = toMap(json); String year = yearMap.keySet().iterator().next(); Map monthMap = ((Map) yearMap.get(year)); String month = monthMap.keySet().iterator().next(); Map dayMap = (Map) monthMap.get(month); String day = dayMap.keySet().iterator().next(); Map hourMap = (Map) dayMap.get(day); System.out.println(yearMap); System.out.println(monthMap); System.out.println(dayMap); System.out.println(hourMap); } public static Map toMap(JSONObject object) throws JSONException { Map map = new HashMap(); Iterator 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 toList(JSONArray array) throws JSONException { List list = new ArrayList(); 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映射转换,我使用此答案中的代码( 将JSON字符串转换为HashMap )

代码是基于json字符串编写的,你可以根据你的需要调整代码,以防多年,月和日出现在json中