我想比较Json文件的两个版本(从git检索)是否有任何差异,并显示被更改的元素的唯一ID。 示例Json: 以下是我的示例Json的版本1:
{
"menu": {
"obj1": {
"id": "2",
"value": "File",
"popup": {
"menuitem": [
{
"value": "New",
"onclick": "CreateNewDoc()"
}
]
}
},
"obj2": {
"id": "1",
"value": "File",
"popup": {
"menuitem": [
{
"value": "New",
"onclick": "CreateNewDoc()"
}
]
}
}
}
}
示例Json的版本2:
{
"menu": {
"obj1": {
"id": "2",
"value": "File",
"popup": {
"menuitem": [
{
"value": "New",
"onclick": "CreateNewDoc()"
}
]
}
},
"obj2": {
"id": "1",
"value": "File",
"popup": {
"menuitem": [
{
"value": "Existing",
"onclick": "Open()"
}
]
}
}
}
}
“ id”是我的唯一标识符,并且我尝试了以下代码来查找差异
JSONParser parser = new JSONParser(new FileReader("D:/FromRepo/new.txt"));
Object obj = parser.parse();
JSONParser parser1 = new JSONParser(new FileReader("D:/FromRepo/new1.txt"));
Object obj1 = parser1.parse();
Gson g = new Gson();
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> firstMap = g.fromJson( obj.toString(), mapType);
Map<String, Object> secondMap = g.fromJson( obj1.toString(), mapType);
// System.out.println(Maps.difference(firstMap, secondMap). entriesDiffering());
Map<String, Object> leftFlatMap = FlatMapUtil.flatten(firstMap);
Map<String, Object> rightFlatMap = FlatMapUtil.flatten(secondMap);
MapDifference<String, Object> difference = Maps.difference(leftFlatMap, rightFlatMap);
System.out.println("\n\nEntries differing\n--------------------------");
difference.entriesDiffering()
.forEach((key, value) -> System.out.println(key + ": " + value));
它给了我以下输出
Entries differing
--------------------------
/menu/obj2/popup/menuitem/0/value: (New, Existing)
/menu/obj2/popup/menuitem/0/onclick: (CreateNewDoc(), Open())
但是有什么方法可以获取更改后的元素的id,在这种情况下为“ id”:“ 1”