Location>code7788 >text

Using JSON Schema to Validate Complex JSON Data in Spring Boot

Popularity:85 ℃/2024-08-06 11:48:05

JSON is a common format we use to pass data when writing APIs, so do you know JSON Schema?

In the field of data exchange, JSON Schema provides strong support for defining and standardizing the structure and rules of JSON data with its powerful standardization capabilities. Through a series of well-designed keywords, JSON Schema is able to describe the properties of data in detail. However, JSON Schema alone is not enough to verify that a JSON instance follows a predefined pattern. This is where the role of JSON Schema validators becomes critical. These validators act as stringent checkers to ensure that each JSON document faithfully reflects the schema definition. JSON Schema validators, as the technical tools for implementing the JSON Schema specification, have flexible integration capabilities that make it easy to incorporate JSON Schema into the development process, regardless of the size of the project, to improve the efficiency and accuracy of data processing. Accuracy of data processing.

Let's take a look at how to validate JSON data in a Spring Boot application using JSON Schema

Try your hand at it.

  1. Create a basic Spring Boot application, if you don't already know how you canClick for a quick start

  2. existAddjson-schema-validatordependencies

<dependency>
  <groupId></groupId>
  <artifactId>json-schema-validator</artifactId>
  <version>1.4.0</version>
</dependency>
  1. Creating a JSON Schema

existsrc/main/resourcesdirectory to create afile, and then create an exhaustive set of validation rules in it, like the following:

{
 "$schema": "/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"
          }
        }
      }
    }
   }
}
  1. Creating a Bean for JsonSchema

Of course, you can also create new directly, but in practice it is recommended to use Spring to manage these instances, such as the following:

@Configuration
public class JsonSchemaConfiguration {

    private static final String SCHEMA_VALIDATION_FILE = "";
   
    @Bean
    public JsonSchema jsonSchema() {
        return JsonSchemaFactory
                .getInstance( .V7 )
                .getSchema( getClass().getResourceAsStream( SCHEMA_VALIDATION_FILE ) );
    }
}
  1. Using JsonSchema
@Slf4j
@Service
public class JsonSchemaValidationService{
  
  @Autowired
  private JsonSchema jsonSchema;
  
  public String validateJson(JsonNode jsonNode){
    
    Set<ValidationMessage> errors = (jsonNode);
    if(()){
      ("event is valid");
    }else{
      ("event is invalid");
     }
      return ();
  }
}
  1. Applications at the Web level

Create a Controller that, upon receiving JSON data from the client, can validate the json data like the following:

import ;
@RestController
public class JsonSchemaController {
    @Autowired
    private JsonSchemaValidationService service;

    @PostMapping("/test")
    public String validateEvent( @RequestBody JsonNode jsonNode ){
       return (jsonNode);
    }
}
  1. Test it.

Launch the Sprint Boot application and then use your favorite http client tool to make a call to the/testinterface to send a test request:

For example, here's a test using Curl:

  • Legitimate requests that comply with the rules:

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

Check passes, return: [], no error message

  • Illegal requests that do not conform to the rules (yet less 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
}'

The calibration fails and an error message is returned:[$.order_id: is missing but it is required]

Well, that's all for today's sharing, I hope it's useful to you. If you are having difficulties in your learning process if any? You can join our super high qualitySpring Technology Exchange GroupThe company's mission is to provide the best possible service to the community, and to participate in exchanges and discussions for better learning and advancement! MoreSpring Boot tutorials can be clicked directly!, welcome favorites & reblogs for support!

Relevant information

  • What is JSON Schema?
  • JSON Schema validator

Welcome to my public number: program ape DD. the first time to understand the cutting-edge industry news, share in-depth technical dry goods, access to high-quality learning resources