Validate JSON in Spring Boot with JSON Schema: Step‑by‑Step Guide
This article explains how to integrate JSON Schema validation into a Spring Boot application, covering dependency setup, schema definition, bean configuration, service implementation, controller exposure, and testing with curl to ensure JSON payloads conform to the defined rules.
Hands‑On JSON Schema Validation in Spring Boot
JSON is the de‑facto format for API data exchange, and JSON Schema provides a powerful way to describe the structure and constraints of JSON documents. To actually enforce those constraints, a JSON Schema validator is required.
Create a basic Spring Boot project.
Add the json-schema-validator dependency to pom.xml:
<dependency>
<groupId>com.networknt</groupId>
<artifactId>json-schema-validator</artifactId>
<version>1.4.0</version>
</dependency>Create a JSON Schema file validation.json under src/main/resources. Example schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Order Event",
"description": "Order event schema for example",
"required": ["order_id", "total_price", "products"],
"properties": {
"order_id": {"type": "string"},
"event": {"enum": ["PLACED", "DELIVERED", "RETURNED"], "type": "string"},
"total_price": {"type": "number", "minimum": 0},
"products": {
"type": "array",
"items": {
"additionalProperties": true,
"required": ["product_id", "price"],
"minItems": 1,
"properties": {
"product_id": {"type": "string"},
"price": {"type": "number", "minimum": 0},
"quantity": {"type": "integer"}
}
}
}
}
}Configure a Spring bean that loads the schema:
@Configuration
public class JsonSchemaConfiguration {
private static final String SCHEMA_VALIDATION_FILE = "validation.json";
@Bean
public JsonSchema jsonSchema() {
return JsonSchemaFactory
.getInstance(SpecVersion.VersionFlag.V7)
.getSchema(getClass().getResourceAsStream(SCHEMA_VALIDATION_FILE));
}
}Implement a service that validates incoming JSON using the bean:
@Slf4j
@Service
public class JsonSchemaValidationService {
@Autowired
private JsonSchema jsonSchema;
public String validateJson(JsonNode jsonNode) {
Set<ValidationMessage> errors = jsonSchema.validate(jsonNode);
if (errors.isEmpty()) {
log.info("event is valid");
} else {
log.info("event is invalid");
}
return errors.toString();
}
}Create a controller that receives JSON payloads and delegates validation:
import com.fasterxml.jackson.databind.JsonNode;
@RestController
public class JsonSchemaController {
@Autowired
private JsonSchemaValidationService service;
@PostMapping("/test")
public String validateEvent(@RequestBody JsonNode jsonNode) {
return service.validateJson(jsonNode);
}
}Testing the Endpoint
Start the Spring Boot application and send requests to /test using any HTTP client. Example with curl:
Valid request (all required fields present):
$ curl --location 'localhost:8080/test' \
--header 'Content-Type: application/json' \
--data '{
"order_id":"order134",
"event":"PLACED",
"products":[{"product_id":"product_1","price":20.5,"quantity":2}],
"total_price":41
}'Response: [] (no errors).
Invalid request (missing order_id):
$ curl --location 'localhost:8080/test' \
--header 'Content-Type: application/json' \
--data '{
"event":"PLACED",
"products":[{"product_id":"product_1","price":20.5,"quantity":2}],
"total_price":41
}'Response: [$.order_id: is missing but it is required] .
By following these steps, you can seamlessly integrate JSON Schema validation into any Spring Boot project, ensuring that incoming JSON payloads strictly adhere to the defined contract.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
