gpt4 book ai didi

java - 合并(合并)2 个 JSONObjects 的最佳方式是什么?

转载 作者:搜寻专家 更新时间:2023-10-30 19:43:06 26 4
gpt4 key购买 nike

合并(合并)两个 JSONObjects 的最佳方式是什么?

JSONObject o1 = {
"one": "1",
"two": "2",
"three": "3"
}
JSONObject o2 = {
"four": "4",
"five": "5",
"six": "6"
}

并且 o1o2 的组合结果必须是

JSONObject result = {
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6"
}

最佳答案

我遇到了同样的问题:我找不到 putAll 方法(而且它没有列在 official reference page 中)。

所以,我不知道这是否是最好的解决方案,但它肯定工作得很好:

//I assume that your two JSONObjects are o1 and o2
JSONObject mergedObj = new JSONObject();

Iterator i1 = o1.keys();
Iterator i2 = o2.keys();
String tmp_key;
while(i1.hasNext()) {
tmp_key = (String) i1.next();
mergedObj.put(tmp_key, o1.get(tmp_key));
}
while(i2.hasNext()) {
tmp_key = (String) i2.next();
mergedObj.put(tmp_key, o2.get(tmp_key));
}

现在,合并后的 JSONObject 存储在 mergedObj

关于java - 合并(合并)2 个 JSONObjects 的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19566081/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com