使用 Jackson 将属性添加到 JSON
所以我是这个jsonStr
[
{
"data": [
{
"itemLabel": "Social Media",
"itemValue": 90
},
{
"itemLabel": "Blogs",
"itemValue": 30
},
{
"itemLabel": "Text Messaging",
"itemValue": 60
},
{
"itemLabel": "Email",
"itemValue": 90
}
]
}
]
我想在数组后面添加一个属性,如下所示data
[
{
"data": [
{
"itemLabel": "Social Media",
"itemValue": 90
},
{
"itemLabel": "Blogs",
"itemValue": 30
},
{
"itemLabel": "Text Messaging",
"itemValue": 60
},
{
"itemLabel": "Email",
"itemValue": 90
}
],
"label": "2007"
}
]
在这里阅读,它说要做这样的事情
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(jsonStr);
((ObjectNode) jsonNode).put("label", "2007");
String json = mapper.writeValueAsString(jsonNode);
return json;
问题是我不断收到错误
java.lang.ClassCastException: com.fasterxml.jackson.databind.node.ArrayNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode
我做错了什么?我目前正在使用 Jackson-core 2.2.2