使用Jackson向JSON添加数组元素

14

我有一个长这样的JSON

[
   {
      "itemLabel":"Social Media",
      "itemValue":90
   },
   {
      "itemLabel":"Blogs",
      "itemValue":30
   },
   {
      "itemLabel":"Text Messaging",
      "itemValue":60
   },
   {
      "itemLabel":"Email",
      "itemValue":90
   },
]

我想把所有这些对象放到一个数组中,以便在我的代码中更轻松地进行操作。因此,我想做类似于:

[
    {
        "data": [
            {
                "itemLabel": "Social Media",
                "itemValue": 90
            },
            {
                "itemLabel": "Blogs",
                "itemValue": 30
            },
            {
                "itemLabel": "Text Messaging",
                "itemValue": 60
            },
            {
                "itemLabel": "Email",
                "itemValue": 90
            }
        ]
    }
]

我该如何使用Jackson添加data数组元素?我主要使用Jackson进行读取,但写入方面经验不多。感谢任何帮助。

1个回答

18

我不完全确定你的意图,可能有一种更优雅的解决方案(使用POJO而不是集合和Jackson的JSON表示),但我想这个例子会让你明白。但如果你有更复杂的处理需求,你可能需要编写自定义的(反)序列化器或类似的东西。使用Jackson 2.3.3编写

ObjectMapper mapper = new ObjectMapper();
JsonNode parsedJson = mapper.readTree(json); //parse the String or do what you already are doing to deserialize the JSON
ArrayNode outerArray = mapper.createArrayNode(); //your outer array
ObjectNode outerObject = mapper.createObjectNode(); //the object with the "data" array
outerObject.putPOJO("data",parsedJson); 
outerArray.add(outerObject);
System.out.println(outerArray.toString()); //just to confirm everything is working

这正是我想要的。我的实现比 OP 中的要复杂一些,但我想保持简单。我只需要将对象放入一个数组中,以便使用 D3.js 进行操作。 - cYn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接