本文介绍了合并两个嵌套的org.json.JSONObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个来自org.json
的JSON对象:第一个是
I have two JSON object from org.json
: the first one is
json1 = {a: {b : {c: val1} } }
第二个是
json2= {a {b: {c2: val2 } } }
是否可以将这两个对象合并为一个对象,如下所示:
is there any way to merge this two object to have one object like this:
result = {a: { b: {c: val1, c2: val2 } } }
我对两个对象的键一无所知,所以我需要动态地循环遍历这些对象并进行合并.有没有内置的方法可以做到这一点.谢谢.
I don't have any idea about the keys of the two objects, so i need to loop dynamically over these objects and do the merge. Is there any built in method to do this trick. Thanks.
推荐答案
static JSONObject merge(JSONObject obj1, JSONObject obj2) {
obj2.forEach((k2, v2) -> obj1.merge(k2, v2, (v1, _v2) ->
v1 instanceof JSONObject && _v2 instanceof JSONObject
? merge((JSONObject)v1, (JSONObject)_v2) : "conflict!!"));
return obj1;
}
这篇关于合并两个嵌套的org.json.JSONObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!