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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23249782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:30:57  来源:igfitidea点击:

Adding an array element to JSON using Hymanson

javajsonHymanson

提问by cYn

I have a JSON that looks like this

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

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

I want to place all of those objects into an array to manipulate it easier in one of my code. Thus I want to do something like

我想将所有这些对象放入一个数组中,以便在我的代码之一中更轻松地对其进行操作。因此我想做类似的事情

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

How do I go about to add in that dataarray element using Hymanson? I have done mostly read using Hymanson but have not done too many writes. Any help would be appreciated. Thank you.

如何data使用 Hymanson添加该数组元素?我主要使用 Hymanson 完成阅读,但没有做过太多写入。任何帮助,将不胜感激。谢谢你。

采纳答案by Aleksandar Stojadinovic

I'm not completely sure what are you intending and there is probably a more elegant solution to this (using POJOs rather than Collections and Hymansons JSON representation), but I guess this example will clear it out to you. But if you have some more complicated processing you might want to write custom (de)serializers or something like that. Written using Hymanson 2.3.3

我不完全确定你的意图是什么,可能有一个更优雅的解决方案(使用 POJOs 而不是 Collections 和 Hymansons JSON 表示),但我想这个例子会让你明白。但是如果你有一些更复杂的处理,你可能想要编写自定义(反)序列化程序或类似的东西。使用 Hymanson 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