在 Java 中比较 2 个 JSON 文件的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6526911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to compare 2 JSON files in Java
提问by James Raitsev
How would you suggest this task is approached?
您建议如何完成这项任务?
The challenge as i see it is in presenting diff information intelligently. Before i go reinventing the wheel, is there an accepted approach of how such a comparison should be handled?
在我看来,挑战在于智能地呈现差异信息。在我重新发明轮子之前,是否有一种可接受的方法来处理这种比较?
采纳答案by JF Beaulieu
You could try the XStream's architecture, handling of JSON mappings
Also, take a look at this post: Comparing two XML files & generating a third with XMLDiff in C#. It's in C# but the logic is the same.
另外,看看这篇文章:Comparing two XML files & generate a third with XMLDiff in C#。它在 C# 中,但逻辑是相同的。
回答by W. Goeman
json-lib
json-lib
What I would do is parse the json data using json-lib. This will result in regular java objects which you can compare using the equals methods. This is only valid though assumingthe guys from json-lib properly implemented the equals method, but that you can easily test.
我会做的是使用json-lib解析 json 数据。这将导致您可以使用 equals 方法进行比较的常规 java 对象。尽管假设来自 json-lib 的人正确实现了 equals 方法,但这仅是有效的,但您可以轻松测试。
回答by Programmer Bruce
This only addresses equality, not differences.
这仅解决平等,而不是差异。
With Hymanson.
与Hyman逊。
ObjectMapper mapper = new ObjectMapper();
JsonNode tree1 = mapper.readTree(jsonInput1);
JsonNode tree2 = mapper.readTree(jsonInput2);
boolean areTheyEqual = tree1.equals(tree2);
From the JavaDoc for JsonNode.equals:
Equality for node objects is defined as full (deep) value equality. This means that it is possible to compare complete JSON trees for equality by comparing equality of root nodes.
节点对象的相等被定义为完全(深)值相等。这意味着可以通过比较根节点的相等性来比较完整的 JSON 树的相等性。
回答by Martin Algesten
I had a similar problem and ended up writing my own library:
我遇到了类似的问题,最终编写了自己的库:
https://github.com/algesten/jsondiff
https://github.com/algesten/jsondiff
It does both diffing/patching.
它同时进行差异/修补。
Diffs are JSON-objects themselves and have a simple syntax for object merge/replace and array insert/replace.
差异本身就是 JSON 对象,并且具有用于对象合并/替换和数组插入/替换的简单语法。
Example:
例子:
original
{
a: { b: 42 }
}
patch
{
"~a": { c: 43 }
}
The ~
indicates an object merge.
该~
指示对象合并。
result
{
a: { b: 42, c: 43 }
}
回答by JLouis
Sr. this is my solution for java code, over my app;
先生,这是我的应用程序上的 Java 代码解决方案;
try {
// Getting The Array "Courses" from json1 & json2
Courses1 =json1.getJSONArray(TAG_COURSES1);
Courses2 = json2.getJSONArray(TAG_COURSES);
//LOOP FOR JSON1
for(int i = 0; i < Courses1.length(); i++){
//LOOP FOR JSON2
for(int ii = 0; ii < Courses2.length(); ii++){
JSONObject courses1 = Courses1.getJSONObject(i);
JSONObject courses2 = Courses2.getJSONObject(ii);
// Storing each json1 item in variable
int courseID1 = courses1.getInt(TAG_COURSEID1);
Log.e("COURSEID2:", Integer.toString(courseID1));
String Rating1 = courses1.getString(TAG_RATING1);
int Status1 = courses1.getInt(TAG_STATUS1);
Log.e("Status1:", Integer.toString(Status1)); //Put the actual value for Status1 in log.
// Storing each json2 item in variable
int courseID2 = courses2.getInt(TAG_COURSEID);
Log.e("COURSEID2:", Integer.toString(courseID)); //Put the actual value for CourseID in log
String Title2 = courses2.getString(TAG_TITLE);
String instructor2 = courses2.getString(TAG_INSTRUCTOR);
String length2 = courses2.getString(TAG_LENGTH);
String rating2 = courses2.getString(TAG_RATING);
String subject2 = courses2.getString(TAG_SUBJECT);
String description2 = courses2.getString(TAG_DESCRIPTION);
//Status1 = 5 from json1; Incomplete, Status1 =-1 Complete
if(Status1 == 5 && courseID2 == courseID1){
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
//Storing the elements if condition is true.
map.put(TAG_COURSEID, Integer.toString(courseID2)); //pend for compare
map.put(TAG_TITLE, Title2);
map.put(TAG_INSTRUCTOR, instructor2);
map.put(TAG_LENGTH, length2);
map.put(TAG_RATING, rating2);
map.put(TAG_SUBJECT, subject2); //show it
map.put(TAG_DESCRIPTION, description2);
//adding HashList to ArrayList
contactList.add(map);
}//if
}//for2 (json2)
} //for1 (json1)
}//Try
Hope this help others, of course, Just put your values and conditions, and the kind of view, in this case; Hashmap over a listview.
当然,希望这对其他人有所帮助,在这种情况下,只需输入您的价值观和条件,以及那种观点;列表视图上的哈希映射。
回答by Didac Montero
For people who are already using Hymanson, I recommend json-patch
对于已经在使用Hymanson 的人,我推荐json-patch
final JsonNode patchNode = JsonDiff.asJson(firstNode, secondNode);
System.out.println("Diff=" + m.writeValueAsString(patchNode));
回答by pacoverflow
I recommend the zjsonpatchlibrary, which presents the diff information in accordance with RFC 6902(JSON Patch). You can use it with Hymanson:
我推荐zjsonpatch库,它根据RFC 6902(JSON Patch)呈现差异信息。您可以将它与Hyman逊一起使用:
JsonNode beforeNode = HymansonObjectMapper.readTree(beforeJsonString);
JsonNode afterNode = HymansonObjectMapper.readTree(afterJsonString);
JsonNode patch = JsonDiff.asJson(beforeNode, afterNode);
String diffs = patch.toString();
This library is better than fge-json-patch(which was mentioned in another answer) because it can detect items being inserted/removed from arrays. Fge-json-patch cannot handle that (if an item is inserted into the middle of an array, it will think that item and every item after that was changed since they are all shifted over by one).
这个库比fge-json-patch(在另一个答案中提到)更好,因为它可以检测从数组中插入/删除的项目。Fge-json-patch 无法处理(如果将一个项目插入到数组的中间,它会认为该项目和之后的每个项目都已更改,因为它们都被移动了一个)。
回答by Cengiz
I've done good experience with JSONAssert.
我在JSONAssert方面有很好的经验。
import org.junit.Test;
import org.apache.commons.io.FileUtils;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
...
@Test
public void myTest() {
String expectedJson = FileUtils.readFileToString("/expectedFile");
String actualJson = FileUtils.readFileToString("/actualFile");
JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.STRICT);
}
...
回答by Ean V
The easiest way to compare json strings is using JSONCompare
from JSONAssertlibrary. The advantage is, it's not limited to structure only and can compare values if you wish:
比较JSON字符串的最简单的方法是使用JSONCompare
从JSONAssert库。优点是,它不仅限于结构,并且可以根据需要比较值:
JSONCompareResult result =
JSONCompare.compareJSON(json1, json2, JSONCompareMode.STRICT);
System.out.println(result.toString());
which will output something like:
这将输出如下内容:
Expected: VALUE1
got: VALUE2
; field1.field2