Adding a property to JSON using Jackson

So my jsonStr is this

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

I want to add a property after a data array like this

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

The reading here says you need to do something like

 ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.readTree(jsonStr); ((ObjectNode) jsonNode).put("label", "2007"); String json = mapper.writeValueAsString(jsonNode); return json; 

The problem is that I get an error all the time

 java.lang.ClassCastException: com.fasterxml.jackson.databind.node.ArrayNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode 

What am I doing wrong? I am currently using Jackson-core 2.2.2

+6
source share
1 answer

Your top level node represents an array, not an object. You need to go one level deeper before you can add a property.

You can use something like this:

 JsonNode elem0 = ((ArrayNode) jsonNode).get(0); ((ObjectNode) elem0).put("label", "2007"); 

Of course, you might want to add some error handling if the structure does not look the way you expect.

+5
source

All Articles