简体   繁体   English

如何在数据未定义时有效地向嵌套 json 添加值

[英]How to add values to nested json efficiently when data is undefined

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.我有一个服务器,当它收到像abc/xyz=yo这样的消息时,我想要的是检查现有的 json 文件,如果它已经存在,那么它将用新值更新文件(仅用于信息/意味着创建嵌套对象和=之后的值是我们要放入 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.如果没有任何值,我可以轻松创建 json,但是当我尝试检查 json object 是否包含它时,问题就来了。 I can use if(object.has(..)) in a for loop but I can not edit the nested object, like我可以在for循环中使用if(object.has(..))但我不能编辑嵌套的 object,比如

//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. 

*/
}
}

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您只需要创建所需的 object 然后再次创建另一个 JSONObject 并将其与原始对象等同起来

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

then you can use o2 to query things like然后你可以使用 o2 来查询类似的东西

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

for more details you can check this out.有关更多详细信息,您可以查看此内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM