[英]Adding property to JSON using Jackson
所以我的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
頂級節點表示數組,而不是對象。 在添加屬性之前,您需要更深入一級。
你可以使用這樣的東西:
JsonNode elem0 = ((ArrayNode) jsonNode).get(0);
((ObjectNode) elem0).put("label", "2007");
當然,如果結構看起來不像您期望的那樣,您可能需要添加一些錯誤處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.