Pregunta

I have a JSON that looks like this

[
   {
      "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 data array element using Jackson? I have done mostly read using Jackson but have not done too many writes. Any help would be appreciated.

¿Fue útil?

Solución

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 Jacksons 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 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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top