Java 使用 Jackson 向 JSON 添加属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23271699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding property to JSON using Hymanson
提问by cYn
So my jsonStr
is this
所以我的jsonStr
是这个
[
{
"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
数组之后添加一个属性
[
{
"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.Hymanson.databind.node.ArrayNode cannot be cast to com.fasterxml.Hymanson.databind.node.ObjectNode
What am I doing wrong? I'm currently using Hymanson-core 2.2.2
我究竟做错了什么?我目前正在使用 Hymanson-core 2.2.2
采纳答案by Henry
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.
当然,如果结构看起来不像您期望的那样,您可能需要添加一些错误处理。