This project demonstrates how to validate incoming JSON payloads in a Spring Boot REST API using JSON Schema.
It ensures that client requests follow a strict contract (correct fields, types, lengths, etc.) before processing.
Maven Dependency to added:-
<dependency>
<groupId>com.networknt</groupId>
<artifactId>json-schema-validator</artifactId>
<version>1.5.9</version>
</dependency>
</dependencies>
Project Structure:-
src/
└── main/
├── java/com/example/demo
│ ├── PayloadController.java
│ ├── JsonValidationService.java
│ └── DemoApplication.java
└── resources/
├── application.properties
├── schema.json
└── samples/
├── valid-payload.json
└── invalid-payload.json
There is a schema.json , file which defines rules for validations for incoming payloads , if payloads fails to validate then it returns the shortcomings in payload
To test use this uri :- http://localhost:8080/api/validate with method POST and in json body provide below payloads
Valid payload
{
"name": "John Doe",
"age": 28,
"email": "john.doe@example.com",
"address": {
"street": "221B Baker Street",
"city": "London"
}
}
and invalid payload:-
{
"name": "John Doe",
"age": 28,
"email": "john.doe@example.com"
}
for invalid we should see this return
[ { "type": "type",
"code": "1029",
"message": "$.address: string found, object expected",
"instanceLocation": "$.address",
"evaluationPath": "$.properties.address.type",
"schemaLocation": "#/properties/address/type",
"messageKey": "type", "arguments": [ "string", "object" ] } ]