JsonSchema官方文檔
入門文檔
入門文檔
生成Schema工具
使用Json的好處(什么是Schema):
- 描述現(xiàn)有的數(shù)據(jù)格式
- 提供清晰的人工和機器可讀文檔
- 完整的數(shù)據(jù)結(jié)構(gòu),有利于自動化測試
- 完整的數(shù)據(jù)結(jié)構(gòu),有利于驗證客戶端提交數(shù)據(jù)的質(zhì)量
什么是JSON Schema
- JSON Schema本身就是一種數(shù)據(jù)結(jié)構(gòu),可以清晰的描述JSON數(shù)據(jù)的結(jié)構(gòu)斋竞。是一種描述JSON數(shù)據(jù)的JSON數(shù)據(jù)。
使用JSON Schema的好處
- JSON Schema 非常適用于基于JSON的HTTP的API删咱。
- JSON Schema從Java的基本數(shù)據(jù)類型中對JSON結(jié)構(gòu)進行校驗,所以對JSON結(jié)構(gòu)的校驗可以理解為對每種不同數(shù)據(jù)類型的相應(yīng)校驗。
- 接口測試中可以快速的定位到自己數(shù)據(jù)格式的正確性瑞你。
JSON模式示例
{
"$schema":"http://json-schema.org/draft-04/schema#",
"title":"book info",
"description":"some information about book",
"type":"object",
"properties":{
"id":{
"description":"The unique identifier for a book",
"type":"integer",
"minimum":1
},
"name":{
"type":"string",
"pattern":"^#([0-9a-fA-F]{6}$",
"maxLength":6,
"minLength":6
},
"price":{
"type":"number",
"multipleOf":0.5,
"maximum":12.5,
"exclusiveMaximum":true,
"minimum":2.5,
"exclusiveMinimum":true
},
"tags":{
"type":"array",
"items":[
{
"type":"string",
"minLength":5
},
{
"type":"number",
"minimum":10
}
],
"additionalItems":{
"type":"string",
"minLength":2
},
"minItems":1,
"maxItems":5,
"uniqueItems":true
}
},
"minProperties":1,
"maxProperties":5,
"required":[
"id",
"name",
"price"
]
}
關(guān)鍵字說明
JOSN模式中常用的關(guān)鍵字(加粗字體為常用字段)
關(guān)鍵字 | 描述 |
---|---|
$schema | The $schema 關(guān)鍵字狀態(tài),這種模式被寫入草案V4規(guī)范希痴。 |
title | 將使用此架構(gòu)提供一個標(biāo)題者甲,title一般用來進行簡單的描述,可以省略 |
description | 架構(gòu)的一點描述砌创,description一般是進行詳細(xì)的描述信息虏缸,可以省略 |
type | 用于約束校驗的JSON元素的數(shù)據(jù)類型,是JSON數(shù)據(jù)類型關(guān)鍵字定義的第一個約束條件:它必須是一個JSON對象 |
properties | 定義屬性:定義各個鍵和它們的值類型纺铭,最小和最大值中要使用JSON文件 |
required | 必需屬性,這個關(guān)鍵字是數(shù)組刀疙,數(shù)組中的元素必須是字符串 |
minimum | 這是約束的值舶赔,并代表可接受的最小值 |
exclusiveMinimum | 如果“exclusiveMinimum”的存在,并且具有布爾值true的實例是有效的谦秧,如果它是嚴(yán)格的最低限度的值 |
maximum | 這是約束的值被提上表示可接受的最大值 |
exclusiveMaximum | 如果“exclusiveMaximum”的存在竟纳,并且具有布爾值true的實例是有效的,如果它是嚴(yán)格的值小于“最大”疚鲤。 |
multipleOf | 數(shù)值實例有效反對“multipleOf”分工的實例此關(guān)鍵字的值锥累,如果結(jié)果是一個整數(shù)。 |
maxLength | 字符串實例的長度被定義為字符的最大數(shù)目 |
minLength | 字符串實例的長度被定義為字符的最小數(shù)目 |
pattern | String實例被認(rèn)為是有效的集歇,如果正則表達(dá)式匹配成功實例 |
聲明JSON模式
由于JSON Schema本身就是JSON桶略,所以當(dāng)一些東西是JSON Schema或者只是JSON的任意一塊時,并不總是很容易分辨诲宇。該 schema設(shè)置schema所使用的參照標(biāo)準(zhǔn)。包含它通常是一種很好的做法姑蓝,盡管不是必需的鹅心。
{ "$schema": "http://json-schema.org/schema#" }
聲明唯一標(biāo)識符(不懂)
最佳做法是將$id屬性包含為每個模式的唯一標(biāo)識符。現(xiàn)在纺荧,只需將其設(shè)置為您控制的域中的URL旭愧,例如:
{ "$id": "http://yourdomain.com/schemas/myschema.json"}
type常見取值
Type其實就是JSON數(shù)據(jù)的基本數(shù)據(jù)類型颅筋,一般是有6種,加上null一共有7種:
type取值 | 對應(yīng)的Java數(shù)據(jù)類型 |
---|---|
object | java.lang.Object |
array | java.util.List |
integer | int(java.lang.Integer) |
number | float(java.lang.Float)或int |
null | null |
boolean | java.lang.Boolean |
string | java.lang.String |
type:Object
示例:
{
"type":"object",
"properties":{
"id":{
"description":"The unique identifier for a book",
"type":"integer",
"minimum":1
},
"price":{
"type":"number",
"minimum":0,
"exclusiveMinimum":true
}
},
"patternProperties":{
"^a":{
"type":"number"
},
"^b":{
"type":"string"
}
},
"additionalProperties":{
"type":"number"
},
"minProperties":1,
"maxProperties":5,
"required":[
"id",
"name",
"price"
]
}
object類型有三個關(guān)鍵字:type(限定類型),properties(定義object的各個字段),required(限定必需字段)
關(guān)鍵字 | 描述 |
---|---|
type | 類型 |
properties | 定義屬性 |
required | 必須屬性 |
maxProperties | 最大屬性個數(shù) |
minProperties | 最小屬性個數(shù) |
additionalProperties | 如果待校驗JSON對象中存在输枯,既沒有在properties中被定義议泵,又沒有在patternProperties中被定義,那么這些一級key必須通過additionalProperties的校驗用押。true or false or object 參考 |
minProperties肢簿、maxProperties說明(用的不是很多)
這兩個關(guān)鍵字的值都是非負(fù)整數(shù)。待校驗的JSON對象中一級key的個數(shù)限制蜻拨,minProperties指定了待校驗的JSON對象可以接受的最少一級key的個數(shù)池充,maxProperties指定了待校驗JSON對象可以接受的最多一級key的個數(shù)
patternProperties
正則表達(dá)式匹配json出現(xiàn)的屬性,該JSON對象的每一個一級key都是一個正則表達(dá)式缎讼,用來匹配value值收夸。
只有待校驗JSON對象中的一級key,通過與之匹配的patternProperties中的一級正則表達(dá)式血崭,對應(yīng)的JSON Schema的校驗卧惜,才算通過校驗。例如夹纫,如果patternProperties對應(yīng)的值如下:
在待校驗JSON對象中咽瓷,所有以S開頭的key的value都必須是number,所有以I開頭的一級key的value都必須是string舰讹。
{
"patternProperties": {
"^S_": {
"type": "number"
},
"^I": {
"type": "string"
}
}
}
type:array
示例:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Product",
"description": "A product from Acme's catalog",
{
"type":"array",
"items":[
{
"type":"string",
"minLength":5
},
{
"type":"number",
"minimum":10
}
],
"additionalItems":{
"type":"string",
"minLength":2
},
"minItems":1,
"maxItems":5,
"uniqueItems":true
}
array有三個單獨的屬性:items,minItems,uniqueItems:
關(guān)鍵字 | 描述 |
---|---|
items | array 每個元素的類型 |
minItems | 約束屬性茅姜,數(shù)組最小的元素個數(shù) |
maxItems | 約束屬性,數(shù)組最大的元素個數(shù) |
uniqueItems | 約束屬性月匣,每個元素都不相同 |
additionalProperties | 約束items的類型钻洒,不建議使用 示例 |
Dependencies | 屬性依賴 用法 |
patternProperties | 用法 |
items
該關(guān)鍵字的值是一個有效的JSON Schema或者一組有效的JSON Schema。
{
"type": "array",
"items": {
"type": "string",
"minLength": 5
}
}
上面的JSON Schema的意思是锄开,待校驗JSON數(shù)組的元素都是string類型素标,且最小可接受長度是5。那么下面這個JSON數(shù)組明顯是符合要求的萍悴,具體內(nèi)容如下:
["myhome", "green"]
下面這個JSON數(shù)組明顯不符合要求
["home", "green"]
當(dāng)該關(guān)鍵字的值是一組有效的JSON Schema時头遭,只有待校驗JSON數(shù)組的所有元素通過items的值中對應(yīng)位置上的JSON Schema的校驗,那么癣诱,整個待校驗JSON數(shù)組才算通過校驗任岸。
這里需要注意的是:如果items定義的有效的JSON Schema的數(shù)量和待校驗JSON數(shù)組中元素的數(shù)量不一致,那么就要采用“取小原則”狡刘。
即享潜,如果items定義了3個JSON Schema,但是待校驗JSON數(shù)組只有2個元素嗅蔬,這時剑按,只要待校驗JSON數(shù)組的前兩個元素能夠分別通過items中的前兩個JSON Schema的校驗疾就,那么,我們認(rèn)為待校驗JSON數(shù)組通過了校驗艺蝴。而猬腰,如果待校驗JSON數(shù)組有4個元素,這時猜敢,只要待校驗JSON數(shù)組的前三個元素能夠通過items中對應(yīng)的JSON Schema的校驗姑荷,我們就認(rèn)為待校驗JSON數(shù)組通過了校驗。
例如缩擂,如果items的值如下:
{
"type":"array",
"items":[
{
"type":"string",
"minLength":5
},
{
"type":"number",
"minimum":10
},
{
"type":"string"
}
]
}
上面的JSON Schema指出了待校驗JSON數(shù)組應(yīng)該滿足的條件鼠冕,數(shù)組的第一個元素是string類型,且最小可接受長度為5胯盯,數(shù)組的第二個元素是number類型懈费,最小可接受的值為10,數(shù)組的第三個元素是string類型博脑。那么下面這兩個JSON數(shù)組明顯是符合要求的憎乙,具體內(nèi)容如下:
["green", 10, "good"]
["helloworld", 11]
下面這兩個JSON數(shù)組卻是不符合要求的,具體內(nèi)容如下:
["green", 9, "good"]
//9小于minimum
["good", 12]
//good小于minLength
additionalItems
該關(guān)鍵字的值是一個有效的JSON Schema叉趣。
需要注意的是泞边,該關(guān)鍵字只有在items關(guān)鍵字的值為一組有效的JSON Schema的時候,才可以使用疗杉,用于規(guī)定超出items中JSON Schema總數(shù)量之外的待校驗JSON數(shù)組中的剩余的元素應(yīng)該滿足的校驗邏輯阵谚。只有這些剩余的所有元素都滿足additionalItems的要求時,待校驗JSON數(shù)組才算通過校驗乡数。
可以這么理解椭蹄,當(dāng)items的值為一組有效的JOSN Schema的時候闻牡,一般可以和additionalItems關(guān)鍵字組合使用净赴,items用于規(guī)定對應(yīng)位置上應(yīng)該滿足的校驗邏輯,而additionalItems用于規(guī)定超出items校驗范圍的所有剩余元素應(yīng)該滿足的條件罩润。如果二者同時存在玖翅,那么只有待校驗JSON數(shù)組同時通過二者的校驗,才算真正地通過校驗割以。
另外金度,需要注意的是,如果items只是一個有效的JSON Schema严沥,那么就不能使用additionalItems猜极,原因也很簡單,因為items為一個有效的JSON Schema的時候消玄,其規(guī)定了待校驗JSON數(shù)組所有元素應(yīng)該滿足的校驗邏輯跟伏。additionalItems已經(jīng)沒有用武之地了丢胚。
強調(diào)一下,省略該關(guān)鍵字和該關(guān)鍵字的值為空J(rèn)SON Schema受扳,具有相同效果携龟。
{
"type": "array",
"items": [
{
"type": "string",
"minLength": 5
},
{
"type": "number",
"minimum": 10
}
],
"additionalItems": {
"type": "string",
"minLength": 2
}
}
上面的JSON Schema的意思是,待校驗JSON數(shù)組第一個元素是string類型勘高,且可接受的最短長度為5個字符峡蟋,第二個元素是number類型,且可接受的最小值為10华望,剩余的其他元素是string類型蕊蝗,且可接受的最短長度為2。
那么立美,下面三個JSON數(shù)組是能夠通過校驗的匿又,具體內(nèi)容如下:
["green", 10, "good"]
["green", 11]
["green", 10, "good", "ok"]
下面JSON數(shù)組是無法通過校驗的,具體內(nèi)容如下:
["green", 10, "a"]
["green", 10, "ok", 2]
minItems建蹄、maxItems
這兩個關(guān)鍵字的值都是非負(fù)整數(shù)碌更。
指定了待校驗JSON數(shù)組中元素的個數(shù)限制,minItems指定了待校驗JSON數(shù)組可以接受的最少元素個數(shù)洞慎,而maxItems指定了待校驗JSON數(shù)組可以接受的最多元素個數(shù)痛单。
另外,需要注意的是劲腿,省略minItems關(guān)鍵字和該關(guān)鍵字的值為0旭绒,具有相同效果。而焦人,如果省略maxItems關(guān)鍵字則表示對元素的最大個數(shù)沒有限制挥吵。
例如,如果限制一個JSON數(shù)組的元素的最大個數(shù)為5花椭,最小個數(shù)為1忽匈,則JSON Schema如下:
"minItems": 1,"maxItems": 5
uniqueItems
該關(guān)鍵字的值是一個布爾值,即boolean(true矿辽、false)丹允。
當(dāng)該關(guān)鍵字的值為true時,只有待校驗JSON數(shù)組中的所有元素都具有唯一性時袋倔,才能通過校驗雕蔽。當(dāng)該關(guān)鍵字的值為false時,任何待校驗JSON數(shù)組都能通過校驗宾娜。
另外批狐,需要注意的是,省略該關(guān)鍵字和該關(guān)鍵字的值為false時前塔,具有相同的效果嚣艇。例如:
"uniqueItems": true
contains
注意:該關(guān)鍵字缘眶,官方說明中支持,但是髓废,有可能你使用的平臺或者第三方工具不支持构捡。所以袱巨,使用需謹(jǐn)慎。
該關(guān)鍵字的值是一個有效的JSON Schema。
只有待校驗JSON數(shù)組中至少有一個元素能夠通過該關(guān)鍵字指定的JSON Schema的校驗贮匕,整個數(shù)組才算通過校驗烦感。
另外喜德,需要注意的是逛绵,省略該關(guān)鍵字和該關(guān)鍵字的值為空J(rèn)SON Schema具有相同效果。
type:string
示例
{
"$schema":"http://json-schema.org/draft-04/schema#",
"title":"Product",
"description":"A product from Acme's catalog",
"type":"object",
"properties":{
"ip":{
"type":"string",
"pattern":"w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*"
},
"host":{
"type":"phoneNumber",
"pattern":"((d{3,4})|d{3,4}-)?d{7,8}(-d{3})*"
},
"email":{
"type":"string",
"format":"email"
}
},
"required":[
"ip",
"host"
]
}
關(guān)鍵字 | 描述 |
---|---|
maxLength | 定義字符串的最大長度频伤,>=0 |
minLength | 定義字符串的最小長度恳谎,>=0 |
pattern | 用正則表達(dá)式約束字符串,只有待校驗JSON元素符合該關(guān)鍵字指定的正則表達(dá)式憋肖,才算通過校驗 |
format | 字符串的格式 |
format該關(guān)鍵字的值只能是以下取值:date-time(時間格式)因痛、email(郵件格式)、hostname(網(wǎng)站地址格式)岸更、ipv4鸵膏、ipv6、uri怎炊、uri-reference谭企、uri-template、json-pointer评肆。
如果待校驗的JSON元素正好是一個郵箱地址债查,那么,我們就可以使用format關(guān)鍵字進行校驗瓜挽,而不必通過pattern關(guān)鍵字指定復(fù)雜的正則表達(dá)式進行校驗盹廷。
type:integer or number
示例
{
"$schema":"http://json-schema.org/draft-04/schema#",
"title":"Product",
"description":"A product from Acme's catalog",
"type":"object",
"properties":{
"price":{
"type":"number",
"multipleOf":0.5,
"maximum":12.5,
"exclusiveMaximum":true,
"minimum":2.5,
"exclusiveMinimum":true
}
},
"required":[
"price"
]
}
integer和number的區(qū)別,integer相當(dāng)于Java中的int類型秸抚,而number相當(dāng)于Java中的int或float類型速和。
number 關(guān)鍵字可以描述任意長度歹垫,任意小數(shù)點的數(shù)字剥汤。
關(guān)鍵字 | 描述 |
---|---|
minimum | 最小值 |
exclusiveMinimum | 如果存在 "exclusiveMinimum" 并且具有布爾值 true,如果它嚴(yán)格意義上大于 "minimum" 的值則實例有效排惨。 |
maximum | 約束屬性吭敢,最大值 |
exclusiveMaximum | 如果存在 "exclusiveMinimum" 并且具有布爾值 true,如果它嚴(yán)格意義上小于 "maximum" 的值則實例有效暮芭。 |
multipleOf | 是某數(shù)的倍數(shù)鹿驼,必須大于0的整數(shù) |
multipleOf
該關(guān)鍵字的值是一個大于0的number欲低,即可以是大于0的int,也可以是大于0的float畜晰。
只有待校驗的值能夠被該關(guān)鍵字的值整除砾莱,才算通過校驗。
如果含有該關(guān)鍵字的JSON Schema如下
{ "type": "integer", "multipleOf": 2 }
2凄鼻、4腊瑟、6都是可以通過校驗的,但是块蚌,3闰非、5、7都是無法通過校驗的峭范,當(dāng)然了财松,2.0、4.0也是無法通過校驗的纱控,但是辆毡,并不是因為multipleOf關(guān)鍵字,而是因為type關(guān)鍵字甜害。
如果含有multipleOf關(guān)鍵字的JSON Schema如下
{ "type": "number", "multipleOf": 2.0 }
2胚迫、2.0、4唾那、4.0都是可以通過校驗的访锻,但是,3闹获、3.0期犬、3、3.0都是無法通過校驗的避诽。
另外龟虎,需要注意的是,省略該關(guān)鍵字則不對待校驗數(shù)值進行該項校驗沙庐。
maximum
該關(guān)鍵字的值是一個number鲤妥,即可以是int,也可以是float拱雏。
該關(guān)鍵字規(guī)定了待校驗元素可以通過校驗的最大值棉安。
省略該關(guān)鍵字,即表示對待校驗元素的最大值沒有要求
exclusiveMaximum
該關(guān)鍵字的值是一個boolean铸抑。
該關(guān)鍵字通常和maximum一起使用贡耽,當(dāng)該關(guān)鍵字的值為true時,表示待校驗元素必須小于maximum指定的值;當(dāng)該關(guān)鍵字的值為false時蒲赂,表示待校驗元素可以小于或者等于maximum指定的值阱冶。
需要注意的是,省略該關(guān)鍵字和該關(guān)鍵字的值為false滥嘴,具有相同效果木蹬。例如:
{ "type": "number", "maximum": 12.3, "exclusiveMaximum": true }
minimum、exclusiveMinimum
minimum若皱、exclusiveMinimum關(guān)鍵字的用法和含義與maximum届囚、exclusiveMaximum相似。唯一的區(qū)別在于是尖,一個約束了待校驗元素的最小值意系,一個約束了待校驗元素的最大值。
type:boolean
對應(yīng)著true或者false
{
"type":"object",
"properties":{
"number":{
"type":"boolean"
}
}
}
進階
type:enum
該關(guān)鍵字的值是一個數(shù)組饺汹,該數(shù)組至少要有一個元素蛔添,且數(shù)組內(nèi)的每一個元素都是唯一的。
如果待校驗的JSON元素和數(shù)組中的某一個元素相同兜辞,則通過校驗迎瞧。否則,無法通過校驗逸吵。
注意凶硅,該數(shù)組中的元素值可以是任何值,包括null扫皱。省略該關(guān)鍵字則表示無須對待校驗元素進行該項校驗足绅。
{
"type":"object",
"properties":{
"street_type":{
"type":"string",
"enum":[
"Street",
"Avenue",
"Boulevard"
]
}
}
}
{
"type":"object",
"properties":{
"street_type":[
"Street",
"Avenue",
"Boulevard"
]
}
}
type:const
該關(guān)鍵字的值可以是任何值,包括null韩脑。
如果待校驗的JSON元素的值和該關(guān)鍵字指定的值相同氢妈,則通過校驗。否則段多,無法通過校驗首量。
省略該關(guān)鍵字則表示無須對待校驗元素進行該項校驗。
注意进苍,該關(guān)鍵字部分第三方工具加缘,并不支持
關(guān)鍵字:$ref
用來引用其他的schema
示例:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Product set",
"type": "array",
"items": {
"title": "Product",
"type": "object",
"properties": {
"id": {
"description": "The unique identifier for a product",
"type": "number"
},
"name": {
"type": "string"
},
"price": {
"type": "number",
"minimum": 0,
"exclusiveMinimum": true
},
"tags": {
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"uniqueItems": true
},
"dimensions": {
"type": "object",
"properties": {
"length": {"type": "number"},
"width": {"type": "number"},
"height": {"type": "number"}
},
"required": ["length", "width", "height"]
},
"warehouseLocation": {
"description": "Coordinates of the warehouse with the product",
"$ref": "http://json-schema.org/geo"
}
},
"required": ["id", "name", "price"]
}
}
關(guān)鍵字definitions
當(dāng)一個schema寫的很大的時候,可能需要創(chuàng)建內(nèi)部結(jié)構(gòu)體觉啊,再使用$ref進行引用拣宏,示列如下:
{
"type": "array",
"items": { "$ref": "#/definitions/positiveInteger" },
"definitions": {
"positiveInteger": {
"type": "integer",
"minimum": 0,
"exclusiveMinimum": true
}
}
}
關(guān)鍵字:allOf
該關(guān)鍵字的值是一個非空數(shù)組,數(shù)組里面的每個元素都必須是一個有效的JSON Schema柄延。
只有待校驗JSON元素通過數(shù)組中所有的JSON Schema校驗蚀浆,才算真正通過校驗。
意思是展示全部屬性搜吧,建議用requires替代市俊,不建議使用,示例如下
{
"definitions":{
"address":{
"type":"object",
"properties":{
"street_address":{
"type":"string"
},
"city":{
"type":"string"
},
"state":{
"type":"string"
}
},
"required":[
"street_address",
"city",
"state"
]
}
},
"allOf":[
{
"$ref":"#/definitions/address"
},
{
"properties":{
"type":{
"enum":[
"residential",
"business"
]
}
}
}
]
}
關(guān)鍵字:anyOf
該關(guān)鍵字的值是一個非空數(shù)組滤奈,數(shù)組里面的每個元素都必須是一個有效的JSON Schema摆昧。
如果待校驗JSON元素能夠通過數(shù)組中的任何一個JSON Schema校驗,就算通過校驗蜒程。
意思是展示任意屬性绅你,建議用requires替代和minProperties替代,示例如下:
{
"anyOf":[
{
"type":"string"
},
{
"type":"number"
}
]
}
關(guān)鍵字:oneOf
該關(guān)鍵字的值是一個非空數(shù)組昭躺,數(shù)組里面的每個元素都必須是一個有效的JSON Schema忌锯。
如果待校驗JSON元素能且只能通過數(shù)組中的某一個JSON Schema校驗,才算真正通過校驗领炫。不能通過任何一個校驗和能通過兩個及以上的校驗偶垮,都不算真正通過校驗。
其中之一
{
"oneOf":[
{
"type":"number",
"multipleOf":5
},
{
"type":"number",
"multipleOf":3
}
]
}
關(guān)鍵字:not
該關(guān)鍵字的值是一個JSON Schema帝洪。
只有待校驗JSON元素不能通過該關(guān)鍵字指定的JSON Schema校驗的時候似舵,待校驗元素才算通過校驗。
非 * 類型
{
"not":{
"type":"string"
}
}
關(guān)鍵字:default
需要特別注意的是葱峡,type關(guān)鍵字的值可以是一個string砚哗,也可以是一個數(shù)組。
如果type的值是一個string砰奕,則其值只能是以下幾種:null蛛芥、boolean、object军援、array常空、number、string盖溺、integer漓糙。
如果type的值是一個數(shù)組,則數(shù)組中的元素都必須是string烘嘱,且其取值依舊被限定為以上幾種昆禽。只要帶校驗JSON元素是其中的一種,則通過校驗蝇庭。
我們項目如何集成JSON Schema
- 引入JSON Schema的依賴
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>3.1.1</version>
</dependency>
- 添加兩個工具包ReadJsonFile醉鳖,JsonValidateUtil
ReadJsonFile:從/src/main/resources目錄中讀取json文件
JsonValidateUtil:校驗json數(shù)據(jù)是否符合schema約定的標(biāo)準(zhǔn)
文件1:ReadJsonFile
package com.mfw.flight.platform.server.util;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonNodeReader;
import java.io.*;
/**
* @Author: sunshaokang
* @Date: 2018/12/29 上午11:23
*/
public class ReadJsonFile {
/**
* 讀取Json文件為String json
*
* @param filePath filePath為文件的相對于resources的路徑
* @return
*/
public static String readJsonFileAsString(String filePath) {
filePath = ReadJsonFile.class.getResource(filePath).getPath();
String jsonStr = "";
try {
File jsonFile = new File(filePath);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 讀取Json文件為JsonNode
*
* @param filePath filePath為文件的絕對路徑
* @return
*/
public static JsonNode readJsonFileAsJsonNode(String filePath) {
JsonNode instance = null;
try {
instance = new JsonNodeReader().fromReader(new FileReader(filePath));
} catch (IOException e) {
e.printStackTrace();
}
return instance;
}
}
文件2:JsonValidateUtil
package com.mfw.flight.platform.server.util;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jsonschema.core.report.ProcessingMessage;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import java.io.IOException;
import java.util.Iterator;
/**
* @Author: sunshaokang
* @Date: 2019/3/27 10:44
*/
@Slf4j
public class JsonValidateUtil {
private final static JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
/**
* 校驗JSON
*
* @param schema json模式數(shù)據(jù)(可以理解為校驗?zāi)0澹? * @param instance 需要驗證Json數(shù)據(jù)
* @return
*/
public static ProcessingReport validatorJsonSchema(String schema, String instance) throws IOException {
ProcessingReport processingReport = null;
JsonNode jsonSchema = JsonLoader.fromString(schema);
JsonNode jsonData = JsonLoader.fromString(instance);
processingReport = factory.byDefault().getValidator().validateUnchecked(jsonSchema, jsonData);
boolean success = processingReport.isSuccess();
if (!success){
Iterator<ProcessingMessage> iterator = processingReport.iterator();
while (iterator.hasNext()){
log.error(String.valueOf(iterator.next()));
}
}
return processingReport;
}
}
-
添加Json文件
/src/main/resources/json目錄下添加json文件
編寫測試類驗證
注意:ReadJsonFile.readJsonFileAsString(filePath)
此方法中filePath為文件相對于resources目錄的路徑,以/開頭哮内。
@Test
public void testschema() throws Exception {
String data = ReadJsonFile.readJsonFileAsString("/json/testString.json");
String schema = ReadJsonFile.readJsonFileAsString("/json/testSchema.json");
ProcessingReport processingReport = validatorJsonSchema(schema, data);
boolean success = processingReport.isSuccess();
System.out.println(success);
// 如下方法可以用來接口自動化
// Assert.assertTrue(report.isSuccess());
}
- 針對response校驗
出參校驗
response.then().assertThat().body(matchesJsonSchemaInClasspath("/json/flightChangeResponse.json"));
bak
matchesJsonSchemaInClasspath 是從 io.restassured.module.jsv.JsonSchemaValidator 這個類中靜態(tài)導(dǎo)入的盗棵,并且推薦靜態(tài)導(dǎo)入這個類中的所有方法
該方法中直接寫json文件名即可
其中ProcessingReport對象中維護了一迭代器壮韭,如果執(zhí)行失敗(執(zhí)行成功時沒有信息)纹因,其提供了一些高級故障信息喷屋。每個錯誤可能包含以下屬性:
- level: 錯誤級別(應(yīng)該就是error)
- schema:引起故障的模式的所在位置的 URI
- instance:錯誤對象
- domain:驗證域
- keyword:引起錯誤的約束key
- found:現(xiàn)在類型
- expected:期望類型