使用REST Assured校验JSON对象数组数据类型报错及多类型校验咨询
报错原因与解决方案
你的报错核心是JSON解析时遇到了<字符,该字符属于HTML内容的起始标记,不符合JSON格式要求,按以下步骤排查修复:
- 修复schema文件格式
确保你的sample.json是纯JSON文件,删除所有HTML转义字符(比如你贴的内容里的"要替换为普通双引号"),不能包含任何<pre>、<code>这类HTML标签,同时修正字段大小写和接口返回对齐,修正后的schema参考:
{ "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "title": { "type": "string" }, "subTitle": { "type": "string" }, "author": { "type": "string" }, "publish_date": { "type": "string" }, "publisher": { "type": "string" }, "pages": { "type": "number" }, "description": { "type": "string" }, "website": { "type": "string" } }, "required": ["title", "subTitle", "author", "publish_date", "publisher", "pages", "description", "website"] }
- 确认接口返回内容
先在测试代码中打印响应内容,确认接口没有返回HTML格式的错误页(比如404、500错误页都会以<开头),修改后的测试代码参考:
public class AppTest { @Test public void verifyJsonSchema() { // GIVEN RestAssured .given() .baseUri("https://bookstore.toolsqa.com/BookStore/v1/Books/9781449325862") // WHEN .when() .get() // 打印响应内容排查问题 .prettyPeek() // THEN .then() .assertThat() .statusCode(200) .body(JsonSchemaValidator.matchesJsonSchemaInClasspath("sample.json")); } }
如果接口实际返回的是带books数组的外层结构,需要对应修改schema,外层增加books数组的定义即可。
不同数据类型校验指导
REST Assured的json-schema-validator完全支持各类数据类型的校验,基于JSON Schema规范实现,常见类型校验规则如下:
- 数字类型校验:可指定
type为integer(整数)或number(浮点数/整数通用),还可配置数值范围、倍数规则:
"pages": { "type": "integer", "minimum": 1, "maximum": 10000, "multipleOf": 1 }
- 日期类型校验:日期在JSON中一般存储为字符串,可通过
format指定标准日期格式,或用pattern自定义正则匹配:
// 标准ISO日期时间校验 "publish_date": { "type": "string", "format": "date-time" } // 自定义格式(比如yyyy-MM-dd) "publish_date": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" }
- 字符/字符串校验:
type指定为string,可配置长度、正则规则,单字符类型直接限制长度为1即可:
// 单字符校验 "grade": { "type": "string", "minLength": 1, "maxLength": 1 } // 普通字符串长度校验 "author": { "type": "string", "minLength": 2, "maxLength": 50 }
内容的提问来源于stack exchange,提问作者Gaurav Marothia
相关产品推荐
相关产品推荐

