组合(合并)2个JSONObjects的最佳方法是什么? [英] What is the best way to combine (merge) 2 JSONObjects?
本文介绍了组合(合并)2个JSONObjects的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
组合(合并)两个 JSONObjects
的最佳方法是什么?
What is the best way to combine (merge) two JSONObjects
?
JSONObject o1 = {
"one": "1",
"two": "2",
"three": "3"
}
JSONObject o2 = {
"four": "4",
"five": "5",
"six": "6"
}
结合 o1
和 o2的结果
必须
JSONObject result = {
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6"
}
推荐答案
我有同样的问题:我找不到 putAll
方法(它没有在官方参考页)。
I have your same problem: I can't find the putAll
method (and it isn't listed in the official reference page).
所以,我不知道如果这是最好的解决方案,但肯定它运作得很好:
So, I don't know if this is the best solution, but surely it works quite well:
//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
Now, the merged JSONObject is stored in mergedObj
这篇关于组合(合并)2个JSONObjects的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文