将List转换为JSON

我已经在我的Wordpress网站上开发了一个钩子,在那里我可以从另一个应用程序更新信息。 我正在使用一个需要特定JSON数据结构的特定插件。 我的Java编程技巧有点生疏,所以我希望有人可以帮我拿下列表:

+------+-------+-----+-------+ | 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结构:

 { "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" } } } 

任何帮助是极大的赞赏。

编辑

我已经创建了以下嵌套映射,但我需要正确的结构来返回指定格式的数据

 Map<String, Map<String, Map>> 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()); 

这取决于您实际意味着用作输入的内容。 您提供的“列表”实际上是一个文本表。 如果你想从每一行中提取实际数字,你可以使用这样的JS正则表达式:

 row = s.match(/\d+/g) 

其中s是文本输入的一行。 如果它是包含您的实际数据的row ,则row length === 4 ,您可以将它们传递给这样的函数以将其添加到您的数据中:

 var data = {}; function addDay(y, m, d, v) { if (!data.hasOwnProperty(y)) { data[y] = {}; } if (!data[y].hasOwnProperty(m)) { data[y][m] = {}; } data[y][m][d] = v; } 

通过为表的每一行重复调用row(a[0], a[1], a[2], a[3]) ,您应该按照自己想要的方式获取对象data

我希望有更优雅的方法来做到这一点(例如,避免将数据作为全局变量),但这应该有效。

使用这些依赖项jackson-databind
jackson的注解
jackson核心

 public class JsonTest { public static void main(String[] args) throws JsonProcessingException { ObjectMapper mapper=new ObjectMapper(); Map dt=new Hashtable(); dt.put("1", "welcome"); dt.put("2", "bye"); String jsonString = mapper.writeValueAsString(dt) System.out.println(jsonString); } } 

这就是你想要的。

得到它以下工作:

  HashMap>> map = new HashMap>>(); for (int i = 0; i < calendarData.size(); i++) { if (!map.containsKey(calendarData.get(i).getYear())) { map.put(calendarData.get(i).getYear(), new HashMap>()); } 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()); } map.get(calendarData.get(i).getYear()).get(calendarData.get(i).getMonth()).put(calendarData.get(i).getDay(), calendarData.get(i).getValue()); }