R
R
Rinat2020-05-29 09:01:03
Java
Rinat, 2020-05-29 09:01:03

Update jsonobject name without loss?

Hello connoisseurs! I have such a problem, I need to pull out the name in the JSONArray array, rename it, and put it back.

Question: without loss, will it have to sort through all the data creating a new array?

an array of this kind: I have an id, let's say 1, and I want to put a new name level-2. also in the future there will be nested json arrays in the array
[{"id":0,"name":"l1"},{"id":1,"name":"l2"}]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Shagiakhmetov, 2020-06-02
@Shagiakhmetov

Without key type checks using Jackson, you can check the array through node.isArray()
private void jsonParse() throws JsonProcessingException {
String str = "[{\"id\":0,\"name\":\"l1\" },{\"id\":1,\"name\":\"l2\"}]";
JsonNode root = new ObjectMapper().readTree(str);
root.forEach(node ​​-> {
System.out.println(node);
if (node.isObject() && node.get("id").asInt() == 1) {
((ObjectNode) node).put ("name", "level-2");
}
});
root.forEach(System.out::print);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question