Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding property to JSON using Jackson

Tags:

java

json

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 the 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"
    }
]

Reading on here it says 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 I keep getting an error

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'm currently using Jackson-core 2.2.2

like image 538
cYn Avatar asked Apr 24 '14 14:04

cYn


1 Answers

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

You could use something like this:

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

Of course you may want to add some error handling if the structure does not look like you expect.

like image 83
Henry Avatar answered Oct 17 '22 03:10

Henry