使用Jackson将数组元素添加到JSON

cYn*_*cYn 11 java json jackson

我有一个看起来像这样的JSON

[
   {
      "itemLabel":"Social Media",
      "itemValue":90
   },
   {
      "itemLabel":"Blogs",
      "itemValue":30
   },
   {
      "itemLabel":"Text Messaging",
      "itemValue":60
   },
   {
      "itemLabel":"Email",
      "itemValue":90
   },
]
Run Code Online (Sandbox Code Playgroud)

我想将所有这些对象放入一个数组中,以便在我的一个代码中更容易地操作它.因此我想做点什么

[
    {
        "data": [
            {
                "itemLabel": "Social Media",
                "itemValue": 90
            },
            {
                "itemLabel": "Blogs",
                "itemValue": 30
            },
            {
                "itemLabel": "Text Messaging",
                "itemValue": 60
            },
            {
                "itemLabel": "Email",
                "itemValue": 90
            }
        ]
    }
]
Run Code Online (Sandbox Code Playgroud)

如何data使用Jackson 添加该数组元素?我大部分时间都是用杰克逊读过的,但没有做太多的写作.任何帮助,将不胜感激.谢谢.

Ale*_*vic 13

我不完全确定你的意图是什么,可能有一个更优雅的解决方案(使用POJO而不是Collections和Jacksons JSON表示),但我想这个例子会清除它给你.但是如果你有一些更复杂的处理,你可能想要编写自定义(de)序列化器或类似的东西.使用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
Run Code Online (Sandbox Code Playgroud)