I use a JSON library called JSONObject
(I don\'t mind switching if I need to).
I know how to iterate over JSONArrays
, but when I parse JSO
Most of the answers here are for flat JSON structures, in case you have a JSON which might have nested JSONArrays or Nested JSONObjects, the real complexity arises. The following code snippet takes care of such a business requirement. It takes a hash map, and hierarchical JSON with both nested JSONArrays and JSONObjects and updates the JSON with the data in the hash map
public void updateData(JSONObject fullResponse, HashMap mapToUpdate) {
fullResponse.keySet().forEach(keyStr -> {
Object keyvalue = fullResponse.get(keyStr);
if (keyvalue instanceof JSONArray) {
updateData(((JSONArray) keyvalue).getJSONObject(0), mapToUpdate);
} else if (keyvalue instanceof JSONObject) {
updateData((JSONObject) keyvalue, mapToUpdate);
} else {
// System.out.println("key: " + keyStr + " value: " + keyvalue);
if (mapToUpdate.containsKey(keyStr)) {
fullResponse.put(keyStr, mapToUpdate.get(keyStr));
}
}
});
}
You have to notice here that the return type of this is void, but sice objects are passed as refernce this change is refelected to the caller.