简体   繁体   English

如何自动化两个JSON响应比较

[英]How to automate two JSON response comparison

I want to compare two json response. 我想比较两个json响应。 I have tried to store the JSON response in a pojo then compared by overiding equals method but my pojo is very large and consist of 10 classes . 我试图将JSON响应存储在pojo中,然后通过覆盖equals方法进行比较,但是我的pojo非常大,由10个类组成。 Is there any other way to compare 还有其他比较方法吗

You may try below code snippet: 您可以尝试以下代码段:

import org.codehaus.jettison.json.JSONObject;
import org.junit.Assert;

import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.filter.cookie.CookieFilter;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

Retrive JSON responses: 检索JSON响应:

Response jsonResponseOne = RestAssured.given().spec(requestSpecification).filter(cookieFilter).relaxedHTTPSValidation().when().///.then().assertThat().extract().response();

Response jsonResponseTwo = RestAssured.given().spec(requestSpecification).filter(cookieFilter).relaxedHTTPSValidation().when().///.then().assertThat().extract().response();

Extract both JSON responses as a string: 将两个JSON响应都提取为字符串:

JSONObject jsonOne = new JSONObject(jsonResponseOne.getBody().asString())
JSONobject jsonTwo = new JSONObject(jsonResponseTwp.getBody().asString())

Compare response using Java: 使用Java比较响应:

Assert.assertEquals(jsonOne, jsonTwo);

If you need the differences between them, try to use zjsonpatch library to detect the differences between two json responses. 如果需要它们之间的差异,请尝试使用zjsonpatch库检测两个json响应之间的差异。

A sample code: 示例代码:

JsonNode json1= jacksonObjectMapper.readTree(jsonString1); JsonNode json2= jacksonObjectMapper.readTree(jsonString2); JsonNode patchNode = JsonDiff.asJson(json1, json2); String diffs = patchNode.toString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM