JsonUtil { public static JSONObject merge( JSONObject req, JSONObject resp ) { if (!req.has("uid") || JSONObject.NULL.equals(req.get("uid"))) req.put("uid", ""); ArrayList<String> keysToRemove = new ArrayList<>(); Set<String> keyset = req.keySet(); for (String key : keyset) { if (isEmptyArray(req.get(key)) || JSONObject.NULL.equals(req.get(key))) keysToRemove.add(key); } for (String keyToRemove : keysToRemove) req.remove(keyToRemove); return mergeRecursive(req, resp); }  static JSONObject merge(
        JSONObject req,
        JSONObject resp
    ); static JSONObject mergeRecursive(
        JSONObject req,
        JSONObject resp
    ); static boolean isEmpty(Object obj); static boolean isEmptyArray(Object obj); static String removeEmptyArrays(JSONObject src); static String removeEmpties(JSONObject src);  }
@Test public void shouldProperlyMerge1311Well() throws Exception { String destString = new String(Files.readAllBytes(Paths.get("src/test/resources/utilTest/well1311dest.json"))); String srcString = new String(Files.readAllBytes(Paths.get("src/test/resources/utilTest/well1311src.json"))); JSONObject dest = new JSONObject(destString); JSONObject src = new JSONObject(srcString); JSONObject merged = JsonUtil.merge(dest, src); String actual = merged.toString(2); String expected = new String(Files.readAllBytes(Paths.get("src/test/resources/utilTest/well1311merged.json"))); assertEquals(expected, actual); }
@Test public void shouldReturnEmptyMergeObject() throws Exception { String destString = "{\"fakeField\": null}"; String srcString = new String(Files.readAllBytes(Paths.get("src/test/resources/utilTest/well1311src.json"))); JSONObject dest = new JSONObject(destString); JSONObject src = new JSONObject(srcString); JSONObject merged = JsonUtil.merge(dest, src); String actual = merged.toString(2); String expected = "{\"uid\": \"uid12333\"}"; assertEquals(expected, actual); }