gpt4 book ai didi

java - 如何在java中使用JSonPath删除json键值

转载 作者:行者123 更新时间:2023-12-01 16:58:49 27 4
gpt4 key购买 nike

我知道它可能是重复的,但仍然发布我的问题,因为我找不到我正在寻找的确切答案。我有一个如下所示的 json 对象(或字符串)。

String str = "{
"status" : {
"timestamp" : "2020-04-30T01:00:00 000Z"
"error" : 0,
"error_message" : null,
"execution" : "completed"
}
}
";

我将从 REST API 测试中获得相同类型的响应,但每次调用后,“时间戳”键将具有与调用时间相关的动态日期和时间值。在这里,我使用 JSONAssert 将我的预期 json 与实际 json 进行整体比较。由于时间戳值不同,它对我来说总是失败。

所以我的问题是在进行任何比较之前,我想从 json 中删除“timestamp”键及其值进行比较,这样它将通过我的情况。我也尝试使用 JsonPath,但没有成功。请问有什么帮助吗?

最佳答案

JSONAssert 允许您在执行断言时创建自定义比较器 [1]。

就您而言,很简单:

JSONAssert.assertEquals(expectedJson,
actualJson,
new CustomComparator(JSONCompareMode.LENIENT,
skips("status.timestamp","another.json.path", ...)));

private static Customization[] skips(String... jsonPaths) {
return Arrays.stream(jsonPaths)
.map(jsonPath -> Customization.customization(jsonPath, (o1, o2) -> true))
.toArray(Customization[]::new);
}

这里我们定义 CustomComparator,其中 customization 接受 JSONPath (status.timestamp) 并接受 ValueMatcher > (lambda) 比较该特定 JSONPath 的两个值。

在我们的例子中,我们将始终返回true,这将有效地跳过该值(无论我们与什么进行比较,该值始终为true)。

编辑:如您所见,CustomComparator 的构造函数采用 Customizationvarargs,因此您可以提供多个字段从比较中忽略。

<小时/>

[1] http://jsonassert.skyscreamer.org/apidocs/org/skyscreamer/jsonassert/Customization.html

[2] http://jsonassert.skyscreamer.org/apidocs/org/skyscreamer/jsonassert/comparator/CustomComparator.html

关于java - 如何在java中使用JSonPath删除json键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61545409/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com