Vinod
Vinod

Reputation: 55

Add new key value to json node in java

I have JSON file :

{
   "id":1,
   "name":"abc",
   "addressDetails":
      {
        "City":"NewYork"
      }
}

I wanted to add one more key-value ("pinCode" : "414141") to the node 'addressDetails'.

I tried using :

ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(new File("D://test.json"));
ObjectNode node = mapper.createObjectNode();
node.with("addressDetails").put("pinCode", "414141"); 

But it's not getting added, Is there any way I can do this ?

Upvotes: 5

Views: 17312

Answers (2)

nan lin
nan lin

Reputation: 388

you can try

you should modify the file path

ObjectMapper mapper = new ObjectMapper();
ObjectNode nodes = mapper.readValue(new File("D:\\test.txt"), 
ObjectNode.class);
nodes.with("addressDetails").put("pinCode", "414141");
mapper.writer().writeValue(new File("D:\\test.txt"), nodes);

Upvotes: 3

cello
cello

Reputation: 5486

The problem with your code is that you add your value to a new JsonObject (node), and not the one (root) that you've read in. So basically, you'll have to add it to root. But to be able to do that, you'll have to cast it to an ObjectNode, as JsonNode does not provide any methods to add to the node.

So, try something like the following:

ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(new File("D://test.json"));
ObjectNode node = (ObjectNode) root;
node.with("addressDetails").put("pinCode", "414141");
mapper.writer().writeValue(new File("D:\\test.txt"), node);

Upvotes: 2

Related Questions