To validate a JSON schema in Java, you can use libraries that provide support for JSON schema validation. JsonSchemaValidator is a Hamcrest matcher that can be used to validate that a JSON document matches a given JSON schema.
Add the following dependency in pom.xml. You can check the latest Maven dependency from here.
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>5.3.2</version>
</dependency>
The sample JSON file is shown below:
{
"data": {
"id": 3,
"email": "emma.wong@reqres.in",
"first_name": "Emma",
"last_name": "Wong",
"avatar": "https://reqres.in/img/faces/3-image.jpg"
},
"support": {
"url": "https://reqres.in/#support-heading",
"text": "To keep ReqRes free, contributions towards server costs are appreciated!"
}
}
I have placed this User.json file in src/test/resources directory in the project.
![](https://qaautomation.expert/wp-content/uploads/2023/12/image-17.png?w=236)
We need to import the below dependency to test the JSON schema:
import static io.restassured.module.jsv.JsonSchemaValidator.
Below is the code that compares the 2 JSON file.
import org.junit.Test;
import java.io.IOException;
import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
public class JsonCompare {
@Test
public void verifyGreaterResponseTime() throws IOException {
// Given
given()
// When
.when()
.get("https://reqres.in/api/users/3")
// Then
.then()
.assertThat()
.body(matchesJsonSchemaInClasspath("User.json"));
}
}
The output of the above program is
![](https://qaautomation.expert/wp-content/uploads/2023/12/image-18.png?w=976)
Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!