不上代码的例子都是耍流氓,我们直接上代码,有如下两个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进去看看到底哪里出了问题??
转载请注明出处 阿布的夏天