不上代碼的例子都是耍流氓,咱們直接上代碼,有以下兩個json串,第一個json比第二個json多了兩個boolean類型值,以及一個string類型值;
{ "boolean1":true, "boolean2":false, "boolean3":true,// 比下面的json多的 "boolean4":true,// 比下面的json多的 "name":"str", "name1":"str" } { "boolean1":true, "boolean2":false, "name":"str" }
public static void main(String[] args) { JSONObject sourceJson = JSON.parseObject("{\n" + "\t\"boolean1\":true,\n" + "\t\"boolean2\":false,\n" + "\t\"boolean3\":true,\n" + "\t\"boolean4\":true,\n" + "\t\"name\":\"str\",\n" + "\t\"name1\":\"str\"\n" + "}"); // 初始配置中,新增的字段添加的庫中 Map<String, Object> paths = JSONPath.paths(sourceJson); System.out.println(JSON.toJSONString(paths)); JSONObject destJson = JSON.parseObject("{\n" + "\t\"boolean1\":true,\n" + "\t\"boolean2\":false,\n" + "\t\"name\":\"str\"\n" + "}"); for (Map.Entry<String, Object> stringObjectEntry : paths.entrySet()) { if(stringObjectEntry.getValue() instanceof JSONObject || stringObjectEntry.getValue() instanceof JSONArray){ continue; } if (!JSONPath.contains(destJson, stringObjectEntry.getKey())) { JSONPath.set(destJson, stringObjectEntry.getKey(), stringObjectEntry.getValue()); System.out.println("key=" + stringObjectEntry.getKey() + " ,value=" + stringObjectEntry.getValue()); } } System.out.println(destJson.toJSONString()); }
運行上述代碼,這裏目標是經過JSONPath解析第一個json,而後對比第二個json中JSONPath,將第一個的多的key,找出來,那正確的狀況應該是找出以下幾項
{ "boolean3":true, "boolean4":true, "name1":"str" }
{"/name":"str","/boolean3":true,"/name1":"str","/boolean2":false,"/":{"boolean2":false,"name":"str","boolean3":true,"boolean1":true,"name1":"str","boolean4":true}} ----------------- key=/boolean3 ,value=true key=/name1 ,value=str ----------------- {"boolean2":false,"name":"str","boolean3":true,"boolean1":true,"name1":"str"}
從運行結果的第一行輸出能夠看到,解析第一個json串的JSONPath答應出來後,就已經沒有了 boolean4的存在,因此咱們直接debug進去看看到底哪裏出了問題??
轉載請註明出處 阿布的夏天java