比较两个JSON [英] Comparing two JSONs

查看:140
本文介绍了比较两个JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中比较两个JSON字符串的最佳方法是什么?我想只能打印出键/值对中的差异。



我使用gson库将其转换为地图并执行断言,但它显示了两个JSON:

  Type type = new TypeToken< Map< String,String>>(){} .getType(); 
Gson gson = new Gson();
Map< String,String> mapExpected = gson.fromJson(expectedJson,type);
Map< String,String> mapResponse = gson.fromJson(jsonResponse,type);
Assert.assertEquals(mapExpected,mapResponse);

有没有更好的方法来做到这一点?



我会实现一个Pair类,它既包含String(key),也包含String然后将所有来自 Map A 的元素设置为Pair(集合中的值)和value() setA )以及另一个Set( setB )中的 Map B 的所有元素



然后计算

  Set< Pair> setA_B = setA.removeAll(setB); 
Set< Pair> setB_A = setB.removeAll(setA);
Set< Pair> result = setA_B.addAll(setB_A);

result 中,只有元素不匹配。如果所有元素匹配(两个原始地图都相等),那么 result 为空。


What's the best way to compare two JSON strings in Java? I want to be able to print out only the difference in key/values pairs.

I'm using gson library to convert it to a map and do assert but it displays both JSONs:

Type type = new TypeToken<Map<String, String>>() {}.getType();
Gson gson = new Gson();
Map<String, String> mapExpected = gson.fromJson(expectedJson, type);
Map<String, String> mapResponse = gson.fromJson(jsonResponse, type);
Assert.assertEquals(mapExpected, mapResponse);

Is there a better way to do this?

解决方案

It is tricky, but it can be done.

I would implement a Pair class that holds both String (key and value), with its corresponding equals() and hashcode();

Then put all elements from Map A as Pair in a Set (setA) and all elements from Map B in another Set (setB)

Then calculate

 Set<Pair> setA_B = setA.removeAll(setB);
 Set<Pair> setB_A = setB.removeAll(setA);
 Set<Pair> result = setA_B.addAll(setB_A);

In result there are only the elements that do not match. If all elements match (both original maps are equal) then result is empty.

这篇关于比较两个JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆