亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

 更新時(shí)間:2024年08月10日 09:23:59   作者:程序猿DD  
在數(shù)據(jù)交換領(lǐng)域,JSON Schema 以其強(qiáng)大的標(biāo)準(zhǔn)化能力,為定義和規(guī)范 JSON 數(shù)據(jù)的結(jié)構(gòu)與規(guī)則提供了有力支持,下面給大家介紹Spring Boot 中使用 JSON Schema 校驗(yàn)復(fù)雜JSON數(shù)據(jù)的過程,感興趣的朋友跟隨小編一起看看吧

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ù)工具,其靈活的集成能力使得無(wú)論項(xiàng)目規(guī)模大小,都能輕松地將 JSON Schema 融入開發(fā)流程,從而提升數(shù)據(jù)處理的效率與準(zhǔn)確性。

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

動(dòng)手試試

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

創(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"
          }
        }
      }
    }
   }
}

創(chuàng)建 JsonSchema 的 Bean

當(dāng)然,你也可以直接new來(lái)創(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 ) );
    }
}

使用 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();
  }
}

在 Web 層的應(yīng)用

創(chuàng)建一個(gè)Controller,當(dāng)接收到來(lái)自客戶端的JSON數(shù)據(jù)之后,就可以像下面這樣對(duì)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);
    }
}

測(cè)試一下

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

比如,下面使用Curl來(lái)進(jìn)行測(cè)試:

符合規(guī)則的合法請(qǐng)求:

$ 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ī)則的非法請(qǐng)求(卻少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]

相關(guān)資料What is JSON Schema?JSON Schema validator

到此這篇關(guān)于Spring Boot 中使用 JSON Schema 來(lái)校驗(yàn)復(fù)雜JSON數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Spring Boot 校驗(yàn)JSON數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Spring中@Transactional注解的使用詳解

    Spring中@Transactional注解的使用詳解

    @Transactional注解是Spring提供的一種聲明式事務(wù)管理方式,這篇文章主要為大家詳細(xì)介紹了@Transactional注解的原理分析及使用,需要的可以參考一下
    2023-05-05
  • 解決沒有@RunWith 和 @SpringBootTest注解或失效問題

    解決沒有@RunWith 和 @SpringBootTest注解或失效問題

    這篇文章主要介紹了解決沒有@RunWith 和 @SpringBootTest注解或失效問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧
    2020-04-04
  • Java單例模式的深入了解

    Java單例模式的深入了解

    這篇文章主要為大家介紹了Java單例模式,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助
    2022-01-01
  • Java開發(fā)實(shí)現(xiàn)的Socket雙向通信功能示例

    Java開發(fā)實(shí)現(xiàn)的Socket雙向通信功能示例

    這篇文章主要介紹了Java開發(fā)實(shí)現(xiàn)的Socket雙向通信功能,結(jié)合實(shí)例形式分析了java基于socket實(shí)現(xiàn)的服務(wù)器端與客戶端雙向通信相關(guān)操作技巧,需要的朋友可以參考下
    2018-01-01
  • Java合并區(qū)間的實(shí)現(xiàn)

    Java合并區(qū)間的實(shí)現(xiàn)

    本文主要介紹了Java合并區(qū)間的實(shí)現(xiàn),通過合理使用集合類和排序算法,可以有效地解決合并區(qū)間問題,具有一定的參考價(jià)值,感興趣的可以了解一下
    2023-08-08
  • Java stringBuilder的使用方法及實(shí)例解析

    Java stringBuilder的使用方法及實(shí)例解析

    這篇文章主要介紹了Java stringBuilder的使用方法及實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-09-09
  • springboot集成es詳解

    springboot集成es詳解

    這篇文章主要介紹了springboot集成es,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-11-11
  • SpringCloud Gateway路由核心原理解析

    SpringCloud Gateway路由核心原理解析

    本文主要介紹了SpringCloudGateway的基礎(chǔ)構(gòu)建塊、工作原理以及核心原理解析,SpringCloudGateway是Spring官方基于SpringSpringBoot和ProjectReactor等技術(shù)開發(fā)的網(wǎng)關(guān),旨在為微服務(wù)架構(gòu)提供一種簡(jiǎn)單而有效的統(tǒng)一的API路由管理方式
    2024-10-10
  • spring?aop?Pointcut?execution規(guī)則介紹

    spring?aop?Pointcut?execution規(guī)則介紹

    這篇文章主要介紹了spring?aop?Pointcut?execution規(guī)則,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • Maven deploy plugin使用方式

    Maven deploy plugin使用方式

    這篇文章主要介紹了Maven deploy plugin使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-11-11

最新評(píng)論