Reputation: 334
I need to just copy metadata from one json node and add it to another. My problem is
ObjectNode.put("key":"value")
overrides the existing data, but i need to add them.
Example:
{"metadata":{ "foo":1, "boo":2}} merged with {"metadata": {"ba":7}}
should be
{"metadata":{"foo":1, "boo":2,"ba":7}}
Should be quite simple, but i don't get it :( So any help would be appreciated!
Upvotes: 2
Views: 7257
Reputation: 121710
You can do this in several ways.
First, using the Jackson API; let us call node
the node you want to modify, newNode
the node you want to merge:
final ObjectNode newMetadata = (ObjectNode) newNode.get("metadata");
final ObjectNode metadata = (ObjectNode) node.get("metadata");
metadata.putAll(newMetadata);
Second, (sorry: self promotion) your target JSON can be used as a JSON Merge Patch; a library I have developped, which uses Jackson (note: 2.2.x, not 1.9.x), has support for it:
final JsonMergePatch patch = JsonMergePatch.fromJson(newNode);
node = patch.apply(node);
Upvotes: 3
Reputation: 19
To add key value pair to json object you just need to take a MAP and put the key values entries in it.now you should take JSONER object. by using serialize method of jsoner you can directly add your MAP to json.
Upvotes: 1