Tengo dos JSONObject con la misma estructura, pero quiero combinarlos de forma que se mantengas las características en común y que a aquellas que sean diferentes le de prioridad al segundo objeto.
Ejemplo:
JSONObject obj1 = new JSONObject("{
"name":"manu",
"age":23,
"occupation":"SE"
}")
JSONObject obj2 = new JSONObject("{
"name":"manu",
"age":23,
"country":"india",
"email" : "foo@bar.com"
}")
Esperado:
JSONObject result = {
"name":"manu",
"age":23,
"occupation":"SE",
"country":"india",
"email" : "foo@bar.com"
}
Intenté con lo siguiente:
JSONObject obj1 = new JSONObject("{\n"
+ "\"name\":\"manu\",\n"
+ "\"age\":23,\n"
+ "\"occupation\":\"SE\"\n"
+ "}");
JSONObject obj2 = new JSONObject("{\n"
+ "\"name\":\"manu\",\n"
+ "\"age\":23,\n"
+ "\"country\":\"india\"\n"
+ "}");
JSONObject result = new JSONObject(obj2.toString());
Iterator<?> keys = obj1.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if (!result.has(key))
result.put(key, obj1.get(key));
}
Pero no lo considero eficiente, pues lo usaré para Jsons muy grandes