英文:
Edit object in nested array in json object with JsonNode
问题
以下是翻译好的内容:
我尝试编辑嵌套数组项中的对象,将 "field2": "desc 2"
更改为 "field2": "xxxx"
,在下面的 JSON 中:
{
"item1": 123,
"item2": "desc 1",
"item3": [
{
"field1": "desc 1",
"field2": "desc 2"
}
]
}
我尝试了这个 解决方案
root = objectMapper.readTree(new File(filePath))
((ObjectNode) root).put("field2", "desc xxxx");
输出为:
{
"item1": 123,
"item2": "desc 1",
"item3": [
{
"field1": "desc 1",
"field2": "desc 2"
}
],
"field2": "desc xxxx"
}
英文:
I was trying to edit object in nested array item "field2": "desc 2"
to "field2": "xxxx"
in below json:
{
"item1": 123,
"item2": "desc 1",
"item3": [
{
"field1": "desc 1",
"field2": "desc 2"
}
]
}
I tried this solution
root = objectMapper.readTree(new File(filePath))
((ObjectNode) root).put("field2", "desc xxxx");
Output was:
{
"item1": 123,
"item2": "desc 1",
"item3": [
{
"field1": "desc 1",
"field2": "desc 2"
}
],
"field2": "desc xxxx"
}
答案1
得分: 2
访问包装的数组首先,然后修改第0个元素:
JsonNode root = objectMapper.readTree(new File(filePath));
ObjectNode item3element0 = (ObjectNode) root.get("item3").get(0);
item3element0.put("field2", "desc xxxx");
...或者构建一个 ArrayNode
,向其中添加元素,然后将其添加到根节点:
JsonNode root = objectMapper.readTree(new File(filePath));
ArrayNode newArr = objectMapper.createArrayNode();
ObjectNode field2Element = objectMapper.createObjectNode();
field2Element.put("field2", "desc xxxx");
newArr.add(field2Element);
root.set("item3", newArr);
英文:
Access the wrapped array first, then modify the 0th element:
JsonNode root = objectMapper.readTree(new File(filePath));
ObjectNode item3element0 = (ObjectNode) root.get("item3").get(0);
item3element0.put("field2", "desc xxxx");
...or construct an ArrayNode
, add elements to it, and add that to the root:
JsonNode root = objectMapper.readTree(new File(filePath));
ArrayNode newArr = objectMapper.createArrayNode();
ObjectNode field2Element = objectMapper.createObjectNode();
field2Element.put("field2", "desc xxxx");
newArr.add(field2Element);
root.set("item3", newArr);
答案2
得分: 2
{
"item1": 123,
"item2": "desc 1",
"item3": [
{
"field1": "desc 1",
"field2": "xxxxxxxxxxxxxx"
}
]
}
英文:
Update json with ObjectMapper and JsonNode (complex json (json arrays and objects )
*
solution :
String json= "{\n" +
" \"item1\": 123,\n" +
" \"item2\": \"desc 1\",\n" +
" \"item3\": [{\"field1\": \"desc 1\", \"field2\": \"desc 2\"}]\n" +
"}";
try {
JsonNode node;
ObjectMapper mapper = new ObjectMapper();
node = mapper.readTree(json);
node.get("item3").forEach(obj -> {
((ObjectNode)obj).put("field2", "xxxxxxxxxxxxxx");
});
System.out.println(node);
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result:
{"item1":123,"item2":"desc 1","item3":[{"field1":"desc 1","field2":"xxxxxxxxxxxxxx"}]}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论