Question

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

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top