[英]java - Compare two json objects with same keys in different order
Given two json objects 给出两个json对象
String a1 = "{\"a\":[{\"b\":\"1\"}, {\"b\":\"2\"}]}";
String a2 = "{\"a\":[{\"b\":\"2\"}, {\"b\":\"1\"}]}";
I'd like to compare them regardless of the order of objects in the array. 无论数组中对象的顺序如何,我都想比较它们。 I'm using
Jackson
but it doesn't work. 我正在使用
Jackson
但它不起作用。
ObjectMapper om = new ObjectMapper().configure(
SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true
);
Map<String, Object> m1 = (Map<String, Object>)(om.readValue(a1, Map.class));
Map<String, Object> m2 = (Map<String, Object>)(om.readValue(a2, Map.class));
System.out.println(m1.equals(m2));
Is there any handy way to compare them properly? 有没有方便的方法来比较它们?
Your om.readValue()
call is returning a Map<String, List<Map<String, Integer>>>
: 你的
om.readValue()
调用返回一个Map<String, List<Map<String, Integer>>>
:
Map<String, List<Map<String, Integer>>> m1 = om.readValue(a1, Map.class);
Map<String, List<Map<String, Integer>>> m2 = om.readValue(a2, Map.class);
System.out.println(m1); //{a=[{b=1}, {b=2}]}
System.out.println(m2); //{a=[{b=2}, {b=1}]}
The lists {b=1}, {b=2}
and {b=2}, {b=1}
are not equal because of their order. 由于订单的顺序,列表
{b=1}, {b=2}
和{b=2}, {b=1}
不相等。 So I converted the list to a HashSet and then ran the comparison: 所以我将列表转换为HashSet然后运行比较:
Map<String, HashSet<Map<String, Integer>>> m1Collected = m1.entrySet().stream()
.map(e -> Map.entry(e.getKey(), new HashSet<>(e.getValue())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
Map<String, HashSet<Map<String, Integer>>> m2Collected = m2.entrySet().stream()
.map(e -> Map.entry(e.getKey(), new HashSet<>(e.getValue())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(m1Collected.equals(m2Collected)); //prints true
You can also use JSONassert with strict mode set to false, to compare JSONs ignoring the order. 您还可以将JSONassert与严格模式设置为false,以比较忽略顺序的JSON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.