JSON Schema is a powerful tool for validating JSON data structure. Schema can be understood as a pattern or rule.
Json Schema defines a set of vocabulary and rules, which are used to define Json metadata, and the metadata is also expressed in the form of Json data. Json metadata defines the specifications that Json data needs to meet. The specifications include members, structures, types, constraints, etc.
JSON Schema is the format description, definition, and template of json. With it, you can generate any json data that meets the requirements
In java, to verify the json data format, use json-schema-validator
. The specific examples are as follows:
<dependency> <groupId>com.github.fge</groupId> <artifactId>json-schema-validator</artifactId> <version>2.2.6</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.3.0</version> </dependency>
jackson -core
and jackson-core
must be introduced, they are required for json-schema-validator
If the data format we want to verify is as follows:
{ "data": [ { "sex": "男", "name": "王小明", "age": 18 }, { "sex": "女", "name": "王小红", "age": 17 } ], "type": "human" }
The outside is type and data, and the inside is an array. The array attributes include sex, name, and age
Writing schema file
{ "type": "object", "properties": { "type": { "type": "string" }, "data": { "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string", "maxLength": 3 }, "sex": { "enum": [ "男", "女" ] }, "age": { "type": "number" } }, "required": [ "name", "sex", "age" ] } } }, "required": [ "type", "data" ] }
The above json describes the data format of the target json. The outer layer must have the fields type and data, and the maximum length of the name is limited maxLength
is 3, and sex is an enumeration value, which can only be male or female. Two strings, age is of type number.
public Map validatorJsonUnchecked(String body) { Map<String, String> map = new HashMap<>(); String filePath = "validator" + File.separator + "validator.json"; ObjectMapper objectMapper = new ObjectMapper(); try { JsonNode jsonNodeSchema = objectMapper.readTree(ResourceUtil.readUtf8Str(filePath)); JsonNode jsonNode = objectMapper.readTree(body); ProcessingReport processingReport = JsonSchemaFactory.byDefault().getValidator().validate(jsonNodeSchema, jsonNode, true); if (!processingReport.isSuccess()) { processingReport.forEach(processingMessage -> { JsonNode missing = processingMessage.asJson().get("missing"); String keyword = processingMessage.asJson().get("keyword").asText(); // 如果缺失字段 if (!Objects.isNull(missing)) { missing.forEach(miss -> { String text = miss.asText(); map.put(text, text + " 字段缺失"); }); // 如果字段超长 } else if ("maxLength".equals(keyword)) { String field = processingMessage.asJson().get("instance").get("pointer").asText(); String value = processingMessage.asJson().get("value").asText(); field = field.substring(field.lastIndexOf("/") + 1); map.put(field, value + " 字段长度过长"); // 如果不在枚举范围内 } else if ("enum".equals(keyword)) { String field = processingMessage.asJson().get("instance").get("pointer").asText(); String value = processingMessage.asJson().get("value").asText(); field = field.substring(field.lastIndexOf("/") + 1); map.put(field, field + "字段值错误," + value + "不在枚举范围内"); } else if ("type".equals(keyword)) { String field = processingMessage.asJson().get("instance").get("pointer").asText(); String found = processingMessage.asJson().get("found").asText(); String expected = processingMessage.asJson().get("expected").toString(); field = field.substring(field.lastIndexOf("/") + 1); map.put(field, field + " 类型错误,现有类型: " + found + ", 预期类型:" + expected); } }); } } catch (IOException | ProcessingException e) { log.error("校验json格式异常", e); } return map; }
The above code first obtains the standard file of json to be verified validator.json
, and then calls JsonSchemaFactory.byDefault() .getValidator().validate(jsonNodeSchema, jsonNode, true)
method verifies the incoming json. Here true
means in-depth inspection. If there is no such parameter, verify the json. When encountering the first error, it returns directly
Then build the test method
public static void main(String[] args) { ValidatorService validatorService = new ValidatorServiceImpl(); Map<String, Object> body = new HashMap<>(); HashMap<String, Object> one = new HashMap<String, Object>() {{ put("name", "王小明"); put("sex", "男"); put("age", 18); }}; HashMap<String, Object> two = new HashMap<String, Object>() {{ put("name", "王小明1"); put("sex", "未知"); put("age", "18"); }}; body.put("type", "human"); body.put("data", Arrays.asList(one,two)); Map map = validatorService.validatorJsonUnchecked(JSONUtil.toJsonStr(body)); System.out.println(map); }
{sex=sex field value error , unknown is not within the enumeration range, name=王小明1 field length is too long, age=age type error, existing type: string, expected type: ["integer","number"]}
If the schema is written using square brackets []
for the list, then only the first one in the array will be checked during verification. It's a pitfall, as follows
{ "type": "object", "properties": { "type": { "type": "string" }, "data": { "type": "array", "items": [ { "type": "object", "properties": { "name": { "type": "string", "maxLength": 3 }, "sex": { "enum": [ "男", "女" ] }, "age": { "type": "number" } }, "required": [ "name", "sex", "age" ] } ] } }, "required": [ "type", "data" ] }
If this is the case, only the first piece of data in the data array will be checked, If there are other errors, no error will be reported! !
The above is the detailed content of How to verify whether the format of json meets the requirements in java. For more information, please follow other related articles on the PHP Chinese website!