Step‑by‑Step JSON Validation in Spring Boot Using JSON Schema
This guide explains how to integrate JSON Schema validation into a Spring Boot application, covering dependency setup, schema definition, bean configuration, service implementation, controller handling, and testing with curl examples to ensure JSON payloads conform to the defined rules.
JSON is a common data‑exchange format, and JSON Schema provides a standardized way to describe and enforce the structure of JSON data. To actually verify JSON instances against a schema, a JSON Schema validator is required.
Hands‑On Example
Create a basic Spring Boot project (see the quick‑start guide if needed).
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 with rules such as:
{
"$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": {"type": "string", "enum": ["PLACED", "DELIVERED", "RETURNED"]},
"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"}
}
}
}
}
}Define 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 JSON against the schema:
@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 to expose a validation endpoint:
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);
}
}Test the endpoint with curl. A valid request returns an empty array, while an invalid request (e.g., missing order_id) returns an error such as [$.order_id: is missing but it is required].
Example of a valid curl request:
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
}'Example of an invalid request (missing order_id) returns the corresponding validation error.
References
Spring Boot quick start: https://www.didispace.com/spring-boot-2/1-2-quick-start.html
Spring technology discussion group: https://www.didispace.com/jiaqun.html
Spring Boot tutorial: https://www.didispace.com/spring-boot-2/
What is JSON Schema?: https://json-schema.org/overview/what-is-jsonschema
JSON Schema validator: https://www.jsonschemavalidator.net/
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.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
