sreisman sreisman - 4 months ago 12
JSON Question

Update JSON values with lambda

I would like to take a JsonNode tree and update each of the values. Can this be done with a lambda expression?

{
"resource": {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
}


I am trying to use the following logic:

JsonNode json = new ObjectMapper().readTree(new ObjectMapper().writeValueAsString(myObject));

ObjectNode rootNode = (ObjectNode) json;
ObjectNode resourceNode = (ObjectNode) rootNode.path("resource");

//Psuedo Code here
resourceNode.forEach(node -> node.value = myFunc(node.value));


Thanks in advance!

Answer

Use .fields() to iterate over the key/value pairs:

resourceNode.fields().forEachRemaining(
    entry -> resourceNode.set(
        entry.getKey(),
        func(entry.getValue())
    )
);
Comments