偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

Spring Boot 中使用 JSON Schema 來校驗(yàn)復(fù)雜 JSON 數(shù)據(jù)

開發(fā) 前端
在數(shù)據(jù)交換領(lǐng)域,JSON Schema 以其強(qiáng)大的標(biāo)準(zhǔn)化能力,為定義和規(guī)范 JSON 數(shù)據(jù)的結(jié)構(gòu)與規(guī)則提供了有力支持。通過一系列精心設(shè)計(jì)的關(guān)鍵字,JSON Schema 能夠詳盡地描述數(shù)據(jù)的各項(xiàng)屬性。

JSON是我們編寫API時(shí)候用于數(shù)據(jù)傳遞的常用格式,那么你是否知道JSON Schema呢?

在數(shù)據(jù)交換領(lǐng)域,JSON Schema 以其強(qiáng)大的標(biāo)準(zhǔn)化能力,為定義和規(guī)范 JSON 數(shù)據(jù)的結(jié)構(gòu)與規(guī)則提供了有力支持。通過一系列精心設(shè)計(jì)的關(guān)鍵字,JSON Schema 能夠詳盡地描述數(shù)據(jù)的各項(xiàng)屬性。然而,僅憑 JSON Schema 本身,尚不足以驗(yàn)證 JSON 實(shí)例是否嚴(yán)格遵循預(yù)設(shè)的模式。此時(shí),JSON Schema 驗(yàn)證器的角色便顯得尤為關(guān)鍵。這些驗(yàn)證器如同嚴(yán)格的檢查官,確保每一個(gè) JSON 文檔都能忠實(shí)地反映出模式的定義。JSON Schema 驗(yàn)證器,作為實(shí)現(xiàn) JSON Schema 規(guī)范的技術(shù)工具,其靈活的集成能力使得無論項(xiàng)目規(guī)模大小,都能輕松地將 JSON Schema 融入開發(fā)流程,從而提升數(shù)據(jù)處理的效率與準(zhǔn)確性。

圖片圖片

下面我們來看看如何在Spring Boot應(yīng)用中使用JSON Schema校驗(yàn)JSON數(shù)據(jù)

動(dòng)手試試

  1. 創(chuàng)建一個(gè)基本的Spring Boot應(yīng)用,如果還不會(huì)可以點(diǎn)擊查看Spring Boot快速入門[1]
  2. 在pom.xml中添加json-schema-validator依賴
<dependency>
  <groupId>com.networknt</groupId>
  <artifactId>json-schema-validator</artifactId>
  <version>1.4.0</version>
</dependency>
  1. 創(chuàng)建JSON Schema

在src/main/resources目錄下創(chuàng)建一個(gè)validation.json文件,然后在里面制定一套詳盡的驗(yàn)證規(guī)則,比如下面這樣:

{
 "$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"
          }
        }
      }
    }
   }
}
  1. 創(chuàng)建 JsonSchema 的 Bean

當(dāng)然,你也可以直接new來創(chuàng)建,但實(shí)戰(zhàn)中還是推薦用Spring管理這些實(shí)例,比如 下面這樣:

@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 ) );
    }
}
  1. 使用 JsonSchema
@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();
  }
}
  1. 在 Web 層的應(yīng)用

創(chuàng)建一個(gè)Controller,當(dāng)接收到來自客戶端的JSON數(shù)據(jù)之后,就可以像下面這樣對json數(shù)據(jù)進(jìn)行校驗(yàn):

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);
    }
}
  1. 測試一下

啟動(dòng) Sprint Boot 應(yīng)用,然后使用你喜歡的http客戶端工具對/test接口發(fā)送測試請求:

比如,下面使用Curl來進(jìn)行測試:

  • 符合規(guī)則的合法請求:
$ 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
}'

校驗(yàn)通過,返回:[],沒有錯(cuò)誤信息

  • 不符合規(guī)則的非法請求(卻少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
}'

校驗(yàn)失敗,將返回錯(cuò)誤信息:[$.order_id: is missing but it is required]

參考資料

[1]Spring Boot快速入門: https://www.didispace.com/spring-boot-2/1-2-quick-start.html

[2]Spring技術(shù)交流群: https://www.didispace.com/jiaqun.html

[3]Spring Boot教程可以點(diǎn)擊直達(dá)!: https://www.didispace.com/spring-boot-2/

[4]What is JSON Schema?: https://json-schema.org/overview/what-is-jsonschema

[5]JSON Schema validator: https://www.jsonschemavalidator.net/

責(zé)任編輯:武曉燕 來源: 程序猿DD
相關(guān)推薦

2025-02-07 09:11:04

JSON對象策略

2021-08-12 10:32:50

Spring Boot參數(shù)校驗(yàn)分組校驗(yàn)

2021-08-10 15:11:27

Spring Boot參數(shù)校驗(yàn)

2011-05-25 13:22:05

PHPJSON

2025-03-21 09:58:59

Python數(shù)據(jù)類型安全

2010-01-05 16:33:35

使用JSON

2024-04-29 07:50:52

C#AES加密

2017-12-27 15:16:35

Spring BootFlyway數(shù)據(jù)庫

2022-11-22 11:47:25

JSON格式外置表單

2010-08-05 13:07:11

FlexJson

2011-07-19 09:08:38

jQuery

2025-01-13 12:46:31

SpringBootJacksonJSON

2022-02-08 17:07:54

Spring BooSpring Aop日志記錄

2012-07-17 16:37:43

json

2023-07-17 18:42:47

gRPCDemo項(xiàng)目

2022-07-26 16:54:08

QuartzJava

2024-12-03 08:00:00

2024-01-09 08:24:49

XMLJSONJavaScript

2025-05-29 01:22:00

FeignJSONRPC

2022-08-11 11:35:43

Vuev-model?表單
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)