将List转换为JSON [英] Convert List into JSON
本文介绍了将List转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经在我的Wordpress网站上开发了一个钩子,在那里我可以从另一个应用程序更新信息。我正在使用一个需要特定JSON数据结构的特定插件。我的Java编程技巧有点生疏,所以我希望有人可以帮我拿下列表:
I've developed a hook into my Wordpress site, where I can update information from another application. I'm using a specific plugin that requires a certain JSON data structure. My Java programming skills are a little rusty, so I was hoping someone could help me take the following List:
+------+-------+-----+-------+
| Year | Month | Day | Value |
+------+-------+-----+-------+
| 2014 | 12 | 22 | 1 |
| 2014 | 12 | 23 | 1 |
| 2014 | 12 | 24 | 1 |
| 2014 | 12 | 25 | 1 |
| 2014 | 12 | 26 | 1 |
| 2015 | 1 | 5 | 1 |
| 2015 | 1 | 6 | 1 |
| 2015 | 1 | 7 | 1 |
| 2015 | 1 | 8 | 1 |
| 2015 | 1 | 9 | 1 |
| 2015 | 1 | 19 | 1 |
| 2015 | 1 | 20 | 1 |
| 2015 | 1 | 21 | 1 |
| 2015 | 1 | 22 | 1 |
| 2015 | 1 | 23 | 1 |
| 2015 | 2 | 2 | 1 |
| 2015 | 2 | 3 | 1 |
| 2015 | 2 | 4 | 1 |
| 2015 | 2 | 5 | 1 |
| 2015 | 2 | 6 | 1 |
+------+-------+-----+-------+
并将其转换为以下JSON结构:
and convert it to the following JSON structure:
{
"2014": {
"12": {
"22": "1",
"23": "1",
"24": "1",
"25": "1",
"26": "1"
}
},
"2015": {
"1": {
"5": "1",
"6": "1",
"7": "1",
"8": "1",
"9": "1",
"19": "1",
"20": "1",
"21": "1",
"22": "1",
"23": "1"
},
"2": {
"2": "1",
"3": "1",
"4": "1",
"5": "1",
"6": "1"
}
}
}
非常感谢任何帮助。
编辑
我是创建了以下嵌套映射,但我需要正确的结构来返回指定格式的数据
I've created the follow nested Maps, but I need the correct structure to return the data in the specified format
Map<String, Map<String, Map<String, String>>> map = new HashMap<>();
map.put("2014", new HashMap(){{put("12",new HashMap(){{put("22","1");}});}});
map.put("2014", new HashMap(){{put("12",new HashMap(){{put("23","1");}});}});
map.put("2014", new HashMap(){{put("12",new HashMap(){{put("24","1");}});}});
map.put("2014", new HashMap(){{put("12",new HashMap(){{put("25","1");}});}});
map.put("2014", new HashMap(){{put("12",new HashMap(){{put("26","1");}});}});
JSONObject json = new JSONObject(map);
System.out.print(json.toString());
推荐答案
使用以下内容:
HashMap<String, HashMap<String, HashMap<String, String>>> map = new HashMap<String, HashMap<String, HashMap<String, String>>>();
for (int i = 0; i < calendarData.size(); i++) {
if (!map.containsKey(calendarData.get(i).getYear())) {
map.put(calendarData.get(i).getYear(), new HashMap<String, HashMap<String, String>>());
}
if (!map.get(calendarData.get(i).getYear()).containsKey(calendarData.get(i).getMonth())) {
map.get(calendarData.get(i).getYear()).put(calendarData.get(i).getMonth(), new HashMap<String, String>());
}
map.get(calendarData.get(i).getYear()).get(calendarData.get(i).getMonth()).put(calendarData.get(i).getDay(), calendarData.get(i).getValue());
}
这篇关于将List转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文