Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a value in the nested JsonNode

Tags:

java

json

I'm trying to update the expiryDate variable in the nested JsonObject to the current date, the structure of the JSON is the following:

{
    "expiryDate" : {
        "type" : "String",
        "value" : "31-12-2019"
    }
} 

I've successfully read the JSON but can put the new property only on the top-level, instead of updating the expiryDate.value property:

JsonNode data = new ObjectMapper().readTree(dataString);
String expiryDate = data.get("expiryDate").get("value").textValue();
((ObjectNode) data).put("05-02-2020");

How can I update the nested property?

like image 594
Karen Avatar asked Mar 04 '23 00:03

Karen


2 Answers

You can use :

JsonNode data = new ObjectMapper().readTree(dataString);
((ObjectNode) data.get("expiryDate")).put("value", "05-02-2020");

Where :

  • ((ObjectNode) data.get("expiryDate")) you get the parent, and then
  • put("value", "05-02-2020") change the value of the nested node

Output

{"expiryDate":{"type":"String","value":"05-02-2020"}}
like image 119
YCF_L Avatar answered Mar 05 '23 14:03

YCF_L


You can user ObjectNode .put and update the existing value below is the tested code

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class Test {

    public static void main(String[] args) throws  Exception {
        String datString = "{ \"expiryDate\" : { \"type\" : \"String\", \"value\" : \"31-12-2019\" } } ";
        JsonNode data = new ObjectMapper().readTree(datString);
        System.out.println(" before update json"+data);
        String expiryDate = data.get("expiryDate").get("value").textValue();
        ((ObjectNode) data.get("expiryDate")).put("value", "05-02-2020");
        System.out.println(" updated json "+data);
    } }
like image 27
Pandit Biradar Avatar answered Mar 05 '23 16:03

Pandit Biradar