![](/img/trans.png)
[英]Adding the json array as a value to a json key using jackson in java
[英]Adding an array element to JSON using Jackson
我有一個看起來像這樣的JSON
[
{
"itemLabel":"Social Media",
"itemValue":90
},
{
"itemLabel":"Blogs",
"itemValue":30
},
{
"itemLabel":"Text Messaging",
"itemValue":60
},
{
"itemLabel":"Email",
"itemValue":90
},
]
我想將所有這些對象放入一個數組中,以便在我的一個代碼中更容易地操作它。 因此我想做點什么
[
{
"data": [
{
"itemLabel": "Social Media",
"itemValue": 90
},
{
"itemLabel": "Blogs",
"itemValue": 30
},
{
"itemLabel": "Text Messaging",
"itemValue": 60
},
{
"itemLabel": "Email",
"itemValue": 90
}
]
}
]
如何使用Jackson添加data
數組元素? 我大部分時間都是用傑克遜讀過的,但沒有做太多的寫作。 任何幫助,將不勝感激。 謝謝。
我不完全確定你的意圖是什么,並且可能有一個更優雅的解決方案(使用POJO而不是Collections和Jacksons JSON表示),但我想這個例子將清除它給你。 但是如果你有一些更復雜的處理,你可能想要編寫自定義(de)序列化器或類似的東西。 使用Jackson 2.3.3編寫
ObjectMapper mapper = new ObjectMapper();
JsonNode parsedJson = mapper.readTree(json); //parse the String or do what you already are doing to deserialize the JSON
ArrayNode outerArray = mapper.createArrayNode(); //your outer array
ObjectNode outerObject = mapper.createObjectNode(); //the object with the "data" array
outerObject.putPOJO("data",parsedJson);
outerArray.add(outerObject);
System.out.println(outerArray.toString()); //just to confirm everything is working
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.