Spring Boot 中使用 JSON Schema 校驗復雜JSON數據的過程
JSON是我們編寫API時候用于數據傳遞的常用格式,那么你是否知道JSON Schema呢?
在數據交換領域,JSON Schema 以其強大的標準化能力,為定義和規(guī)范 JSON 數據的結構與規(guī)則提供了有力支持。通過一系列精心設計的關鍵字,JSON Schema 能夠詳盡地描述數據的各項屬性。然而,僅憑 JSON Schema 本身,尚不足以驗證 JSON 實例是否嚴格遵循預設的模式。此時,JSON Schema 驗證器的角色便顯得尤為關鍵。這些驗證器如同嚴格的檢查官,確保每一個 JSON 文檔都能忠實地反映出模式的定義。JSON Schema 驗證器,作為實現(xiàn) JSON Schema 規(guī)范的技術工具,其靈活的集成能力使得無論項目規(guī)模大小,都能輕松地將 JSON Schema 融入開發(fā)流程,從而提升數據處理的效率與準確性。

下面我們來看看如何在Spring Boot應用中使用JSON Schema校驗JSON數據
動手試試
- 創(chuàng)建一個基本的Spring Boot應用,如果還不會可以點擊查看快速入門
- 在
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)建一個validation.json文件,然后在里面制定一套詳盡的驗證規(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
當然,你也可以直接new來創(chuàng)建,但實戰(zhàn)中還是推薦用Spring管理這些實例,比如 下面這樣:
@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 層的應用
創(chuàng)建一個Controller,當接收到來自客戶端的JSON數據之后,就可以像下面這樣對json數據進行校驗:
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);
}
}測試一下
啟動 Sprint Boot 應用,然后使用你喜歡的http客戶端工具對/test接口發(fā)送測試請求:
比如,下面使用Curl來進行測試:
符合規(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
}'校驗通過,返回:[],沒有錯誤信息
不符合規(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
}'校驗失敗,將返回錯誤信息:[$.order_id: is missing but it is required]
相關資料What is JSON Schema?JSON Schema validator
到此這篇關于Spring Boot 中使用 JSON Schema 來校驗復雜JSON數據的文章就介紹到這了,更多相關Spring Boot 校驗JSON數據內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決沒有@RunWith 和 @SpringBootTest注解或失效問題
這篇文章主要介紹了解決沒有@RunWith 和 @SpringBootTest注解或失效問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Java開發(fā)實現(xiàn)的Socket雙向通信功能示例
這篇文章主要介紹了Java開發(fā)實現(xiàn)的Socket雙向通信功能,結合實例形式分析了java基于socket實現(xiàn)的服務器端與客戶端雙向通信相關操作技巧,需要的朋友可以參考下2018-01-01
spring?aop?Pointcut?execution規(guī)則介紹
這篇文章主要介紹了spring?aop?Pointcut?execution規(guī)則,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11

