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?
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 nodeOutput
{"expiryDate":{"type":"String","value":"05-02-2020"}}
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);
} }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With