Backend Development 7 min read

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.

macrozheng
macrozheng
macrozheng
Validate JSON in Spring Boot with JSON Schema: Step‑by‑Step Guide

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

:

<code>&lt;dependency&gt;
  &lt;groupId&gt;com.networknt&lt;/groupId&gt;
  &lt;artifactId&gt;json-schema-validator&lt;/artifactId&gt;
  &lt;version&gt;1.4.0&lt;/version&gt;
&lt;/dependency&gt;</code>

Create a JSON Schema file

validation.json

under

src/main/resources

. Example schema:

<code>{
  "$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"}
        }
      }
    }
  }
}</code>

Configure a Spring bean that loads the schema:

<code>@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));
    }
}</code>

Implement a service that validates incoming JSON using the bean:

<code>@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();
    }
}</code>

Create a controller that receives JSON payloads and delegates validation:

<code>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);
    }
}</code>

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):

<code>$ 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
}'</code>

Response: [] (no errors).

Invalid request (missing

order_id

):

<code>$ 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
}'</code>

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.

backendJavaJSON SchemaValidationSpring BootAPI
macrozheng
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.