We don’t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
The community reviewed whether to reopen this question 2 years ago and left it closed:
Original close reason(s) were not resolved
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(28)
尝试 Skyscreamer 的 JSONAssert。
它的非严格模式有两个主要优点,使其不那么脆弱:
在严格模式下它的行为更像 json-lib 的测试类。
测试如下所示:
JSONAssert.assertEquals() 调用中的参数为 expectedJSONString、actualDataString 和 isStrict。
结果消息非常清晰,这在比较非常大的 JSON 对象时非常重要。
Try Skyscreamer's JSONAssert.
Its non-strict mode has two major advantages that make it less brittle:
In strict mode it behaves more like json-lib's test class.
A test looks something like this:
The parameters in the JSONAssert.assertEquals() call are expectedJSONString, actualDataString, and isStrict.
The result messages are pretty clear, which is important when comparing really big JSON objects.
作为一般架构点,我通常建议不要让对特定序列化格式的依赖超出存储/网络层;因此,我首先建议您考虑测试您自己的应用程序对象之间的相等性,而不是它们的 JSON 表现形式。
话虽如此,我目前是 Jackson 的忠实粉丝,我快速阅读了他们的 ObjectNode.equals() 实现建议是否进行您想要的集合成员资格比较:
As a general architectural point, I usually advise against letting dependencies on a particular serialization format bleed out beyond your storage/networking layer; thus, I'd first recommend that you consider testing equality between your own application objects rather than their JSON manifestations.
Having said that, I'm currently a big fan of Jackson which my quick read of their ObjectNode.equals() implementation suggests does the set membership comparison that you want:
使用 GSON
编辑:自 GSON v2.8.6 实例起方法
JsonParser.parse
已弃用。您必须使用静态方法JsonParser.parseString
:Using GSON
Edit: Since GSON v2.8.6 the instance method
JsonParser.parse
is deprecated. You have to use the static methodJsonParser.parseString
:我会做以下事情,
I would do the following,
使用此库: https://github.com/lukas-krecan/JsonUnit
Pom:
IGNORING_ARRAY_ORDER - 忽略数组中的顺序
Use this library: https://github.com/lukas-krecan/JsonUnit
Pom:
IGNORING_ARRAY_ORDER - ignores order in arrays
您可以尝试使用 json-lib 的 JSONAssert 类:
给出:
You could try using json-lib's JSONAssert class:
Gives:
如果您已经在使用 JUnit,最新版本现在采用 Hamcrest。它是一个通用匹配框架(对于单元测试特别有用),可以扩展以构建新的匹配器。
有一个名为 hamcrest-json 的小型开源库,具有 JSON 感知匹配功能。它有完善的文档记录、测试和支持。以下是一些有用的链接:
使用 JSON 库中的对象的示例代码
org.json.simple
:您可以选择(1) 允许“任意顺序”数组,(2) 忽略额外字段。
由于 Java 有多种 JSON 库(
Jackson
、GSON
、json-lib
等),因此>hamcrest-json
支持 JSON 文本(如java.lang.String
),并原生支持 Douglas Crockford 的 JSON 库org.json
中的对象。最后,如果您不使用 JUnit,则可以直接使用 Hamcrest 进行断言。 (我在这里写过。)
If you are already using JUnit, the latest version now employs Hamcrest. It is a generic matching framework (especially useful for unit testing) that can be extended to build new matchers.
There is a small open source library called
hamcrest-json
with JSON-aware matches. It is well documented, tested, and supported. Below are some useful links:Example code using objects from the JSON library
org.json.simple
:Optionally, you may (1) allow "any-order" arrays and (2) ignore extra fields.
Since there are a variety of JSON libraries for Java (
Jackson
,GSON
,json-lib
, etc.), it is useful thathamcrest-json
supports JSON text (asjava.lang.String
), as well as natively supporting objects from Douglas Crockford's JSON libraryorg.json
.Finally, if you are not using JUnit, you can use Hamcrest directly for assertions. (I wrote about it here.)
您可以尝试 JsonUnit。它可以比较两个 JSON 对象并报告差异。它建立在杰克逊之上。
例如
结果为
You can try JsonUnit. It can compare two JSON objects and report differences. It's built on top of Jackson.
For example
Results in
我所做的一件事非常有效,就是将两个对象读入 HashMap,然后与常规的 assertEquals() 进行比较。它将调用哈希图的 equals() 方法,该方法将递归地比较内部的所有对象(它们将是其他哈希图或某些单值对象,如字符串或整数)。这是使用 Codehaus 的 Jackson JSON 解析器完成的。
如果 JSON 对象是数组,则可以使用类似的方法。
One thing I did and it works wonders is to read both objects into HashMap and then compare with a regular assertEquals(). It will call the equals() method of the hashmaps, which will recursively compare all objects inside (they will be either other hashmaps or some single value object like a string or integer). This was done using Codehaus' Jackson JSON parser.
A similar approach can be used if the JSON object is an array instead.
我正在使用这个,并且对我来说效果很好(使用 org.json.*):
I'm using this, and works fine for me (with org.json.*):
对于 org.json,我推出了自己的解决方案,这是一种与 JSONObject 实例进行比较的方法。我没有在该项目中使用复杂的 JSON 对象,因此我不知道这是否适用于所有场景。另外,考虑到我在单元测试中使用它,我没有花精力进行优化。这里是:
For org.json I've rolled out my own solution, a method that compares to JSONObject instances. I didn't work with complex JSON objects in that project, so I don't know whether this works in all scenarios. Also, given that I use this in unit tests, I didn't put effort into optimizations. Here it is:
对于像我这样想使用 Jackson 进行此操作的人,可以使用 json-unit。
这些错误提供了有关不匹配类型的有用反馈:
For those like me wanting to do this with Jackson, you can use json-unit.
The errors give useful feedback on the type of mismatch:
您可以使用 zjsonpatch 库,它根据 RFC 6902 (JSON Patch) 提供 diff 信息。它非常容易使用。请访问其描述页面了解其用法
You can use zjsonpatch library, which presents the diff information in accordance with RFC 6902 (JSON Patch). Its very easy to use. Please visit its description page for its usage
我知道它通常仅考虑用于测试,但您可以在 Hamcrest JSON 中使用 Hamcrest JSON comparitorSameJSONAs。
Hamcrest JSON SameJSONAs
I know it is usually considered only for testing but you could use the Hamcrest JSON comparitorSameJSONAs in Hamcrest JSON.
Hamcrest JSON SameJSONAs
但是
org.json
确实支持这个!使用similar()
而不是equals()
。But
org.json
does support this! Usesimilar()
instead ofequals()
.这可能会对那些使用 Spring Framework 的人有所帮助。您可以重用内部用于对 ResultActions 进行断言的内容(用于控制器测试):
导入:org.springframework.test.util.JsonExpectationsHelper
并且您可以编写会破坏的测试带有详细输出:
测试代码:
This may help those working with Spring Framework. You may reuse what is used internally for doing assertions on ResultActions (for controller testing):
Import: org.springframework.test.util.JsonExpectationsHelper
And you can write tests that break with verbose output:
Test code:
为了比较 json,我建议使用我的库 JSONCompare:
https://github.com/fslev/json-compare
For comparing jsons I recommend using my library, JSONCompare:
https://github.com/fslev/json-compare
我将在 http://json.org/java/ 获取库,并修改
equals
方法进行深度相等测试。为了确保它的工作与子级的顺序无关,您所需要做的就是用TreeMap
替换内部映射,或者使用Collections.sort()
之类的东西>。I'd take the library at http://json.org/java/, and modify the
equals
method of JSONObject and JSONArray to do a deep equality test. To make sure that it works regradless of the order of the children, all you need to do is replace the inner map with aTreeMap
, or use something likeCollections.sort()
.试试这个:
Try this:
空手道正是您正在寻找的。这是一个示例:(
免责声明:此处为 dev)
Karate is exactly what you are looking for. Here is an example:
(disclaimer: dev here)
我所做的是使用 gson 将 json 转换为映射,并使用 assertj 比较映射:
结果是所有属性之间的很好的比较,递归地!
What I did is converting the jsons into maps using gson and comparing the maps using assertj:
The result is a nice comparison between all attributes, recursively!!!
这是使用 Jackson ObjectMapper 的代码。要了解更多信息,请阅读这篇文章。
Here is the code using Jackson ObjectMapper. To know more read this article.
其他似乎都不太正常,所以我写了这个:
Nothing else seemed to work quite right, so I wrote this:
以下代码将更有助于比较两个 JsonObject、JsonArray、JsonPrimitive 和 JasonElements。
Following code will be more helpful to compare two JsonObject, JsonArray, JsonPrimitive and JasonElements.
https://tech. blobcity.com/2018/09/02/json-equals-in-java-to-compare-two-jsons
https://tech.blobcity.com/2018/09/02/json-equals-in-java-to-compare-two-jsons
查看答案,我尝试了 JSONAssert 但失败了。所以我使用 Jackson 和 zjsonpatch。我在此处的SO答案中发布了详细信息。
Looking at the answers, I tried JSONAssert but it failed. So I used Jackson with zjsonpatch. I posted details in the SO answer here.
JSONObject
中的toMap()
已经可以很好地处理嵌套对象和数组了。由于 java.util.Map 接口指定检查映射而不是顺序,因此比较 Map 是可以的,而且也是递归的。
它适用于任何顺序和嵌套元素。
然而,它不能处理额外/忽略的元素。如果这些已知,您可以在调用地图上的
equals
之前删除它们。toMap()
inJSONObject
works fine with nested objects and arrays already.As the java.util.Map interface specifies to check the mappings and not the order, comparing the Maps is fine and also recursive.
It will work fine with any order and nested elements.
It will NOT however work with extra/ignored elements. If those are known you can remove them before calling
equals
on the maps.ModelAssert - https://github.com/webcompere/model-assert 执行此操作。默认情况下,它更喜欢按顺序排列 JSON,但它可以使用对象键和数组元素的宽松顺序:
此断言是 AssertJ 风格 - 即使用流畅的 DSL。 ModelAssert 还可以用于使用相同的 DSL 构建 Hamcrest 或 Mockito 匹配器。
Json 可以是
String
、File
、JacksonJsonNode
,甚至是自发转换为 JSON 进行比较的 POJO。还支持 yml。
ModelAssert - https://github.com/webcompere/model-assert does this. By default, it prefers the JSON to be in order, but it can use relaxed order of object keys and array elements:
This assertion is AssertJ style - i.e. using a fluent DSL. ModelAssert can also be used to build Hamcrest or Mockito matchers with the same DSL.
The Json can be a
String
,File
, JacksonJsonNode
, or even a POJO that is spontaneously converted to JSON for comparison.There's also support for yml.