对比两个Json对象是否一致

在做api迁移的时候,需要比较老api和新api的返回结果是否一致,之前一直用到的是将json字符串转成Map然后对比

ObjectMapper objectMapper = new ObjectMapper();
Map<String, String> oldJsonMap = objectMapper.readValue( oldResponse, Map.class );
Map<String, String> newJsonMap = objectMapper.readValue( newResponse, Map.class );
if ( oldJsonMap.equals( newJsonMap ) )
{
  log.info( name + " match test successful" );
}

这种做法可以对比大部分情况的返回结果,而且不分json字段顺序,但是对于一些返回内容特别长的json字符串对比就会对比有问题(返回结果是一致的,但是oldJsonMap.equals( newJsonMap )总是返回false,暂时没有搞清楚原因)。

后来google了下其他解决方案,找到了一种个人认为比较好的方法:使用org.skyscreamer包下的JSONAssert.assertEquals()方法。

JSONAssert.assertEquals( oldResponse, newResponse, false );

gradle添加依赖包:compile "org.skyscreamer:jsonassert:1.5.0"

猜你喜欢

转载自blog.csdn.net/wessiyear/article/details/80736591