How to add values to nested json efficiently when data is undefined

Viewed 142

I've a server when it receives a message like abc/xyz=yo then what I want is to check the existing json file and if this already exists then it will update the file with new value(just for the info. / means creating nested objects and value after = is the value we want to put in json.

I can easily create json if there isn't any value but the problem comes when I try to check if the json object contains that. I can use if(object.has(..)) in a for loop but I can not edit the nested object, like

//abc/xyz would be spited into String[] children = string.split("/"))


JSONObject object = new JSONObject(myJSONString);
JSONObject tmpObjext = object.getJSONObject("root")
for(int i=0;i=children.length;i++){
if(object.has(children[i]){
tmpObject = tmpObject.getJSONObject(children[i[)

/*let the initial json be like 
{"root":{"abc":{"xyz"="yo"}}}
so the above code will return the final object i.e. {"xyz":"yo"}


so I tried getting rest of the children i.e. "abc"
and create a new json with updated value but as it
would be user generated I don't know how many
times it would be nested (in this case it's nested
twice once to add it to root and once to acc xyz to abc)

so I'll again have {"abc":{"xyz":"yo"}} so that I
can put it in main object like object.put("root",newJSON) but this would create
problem if there were multiple objects in it like 
{"abc":{"xyz":"yo"}{"pqr":"yoi"}} so if I just
changed the xyz value and regenerate json and put
in root it will just put updated value of xyz and
remove the pqr field. 

*/
}
}
1 Answers

I figured out how we can do this. you just need to create the desired object then again create another JSONObject and equate it with original one like

JSONObject o1 = new JSONObject(yourJSON);
JSONObject o2 = o1.getJSONObject("yourRootIfAny");

then you can use o2 to query things like

for (your children){
if(o2.has(child)){
o2 = o2.getJSONObject(child)
}
}

for more details you can check this out.

Related