I want to merge JSON Object to master JSON Object at required depth
Master JSON
{
"data":{
"barrel":{
"length":100,
"stage":[0,1,2]
},
"a":100,
"b":200
}
}
New JSON Object to be added at path data.barrel
{
"width":100
}
Required Output
{
"data":{
"barrel":{
"length":100,
"stage":[0,1,2],
"width":100
},
"a":100,
"b":200
}
}
Tried following code
String str = "{"data":{"barrel":{"length":100,"stage":[0,1,2]},"a":100,"b":200}}";
String newstr = "{"width":100}";
String path = "data.barrel";
JSONObject jonew = new JSONObject(newstr);
Josson josson = Josson.fromJsonString(str);
Josson jossonNew = Josson.fromJsonString(jonew.toString());
System.out.println(josson.getNode(path));
JsonNode jn = josson.getNode(path);
JsonNode jnNew = jossonNew.getNode();
Iterator<String> keys = jonew.keys();
while (keys.hasNext()) {
String key = keys.next();
if (!jn.has(key))
((ObjectNode) jn).set(key, jnNew.get(key));
}
Output
{"length":100,"stage":[0,1,2],"width":100}
I am able to add child as a separate object, but not to the parent JSON Object
I need a generic way as the path and depth can be varying
Regards,
Pranav
2
Answers
and then you can invoke this method
Deserialization
By Parameters
By Inline
Output