3

I want these:

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

to Merge like this:

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

the method putALL doesn't work, getNames doesn't work either.

manuel_k
  • 575
  • 1
  • 8
  • 22

2 Answers2

4

Manually

 JSONObject obj = new JSONObject("first json");
 JSONObject obj2 = new JSONObject("second json");
 Iterator<String> keys = obj2.keys();
 while( keys.hasNext() ) {
     String key =  keys.next();
     obj.put(key, obj2.optString(key);
 } 

edit

or if your JSONObject contains different types of values you can use opt(String key) which returns a generic Object. Thanks to @Selvin for pointing that out

check for typo

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
  • of course it will work only for strings properties ... – Selvin Dec 03 '15 at 11:03
  • it works with your example, that gives the point. – guillaume girod-vitouchkina Dec 03 '15 at 11:05
  • Interesting ... json.org API has no method to check the property type ... so it is not possible to make it more generic ... on the other hand ... removing last `}` from the first json and first `{` from second and concate those string with coma inside should do the thing .... – Selvin Dec 03 '15 at 11:05
  • json has still the [get(key)](http://www.json.org/javadoc/org/json/JSONObject.html#get(java.lang.String)) which returns a generic object, that *should* cover more or less all the cases @Selvin. The string solution would definitely work, but I am not a fun of it (my personal taste) – Blackbelt Dec 03 '15 at 11:14
  • 1
    uh, forgot about this method(or opt(key) ) ... so `obj.put(key, obj2.opt(key))` should do the thing for other types – Selvin Dec 03 '15 at 11:17
  • thank you, you are great – manuel_k Dec 03 '15 at 13:01
  • @manuel_k, you are welcome – Blackbelt Dec 03 '15 at 13:03
0

for complex types: use java types:

1 convert to a map (not so easy)

Convert a JSON String to a HashMap

2 append the maps

3 convert the map to json (easy)

new JSONObject(map);

Community
  • 1
  • 1