【发布时间】:2020-05-08 20:07:13
【问题描述】:
我正在尝试使用 if/then/else 来验证 json,但 if/else/part 没有按预期进行验证。 当我将“example.json”与“parentSchema.json”文件进行比较时。假设我没有在文件中提供“名称”,所以会抛出一个错误。但它没有抛出任何错误并成功验证.
尝试了多个值和多个场景,包括 allOf 等。尝试在不同的网站(在线编辑器)中验证我的架构,它在那里正确执行并按预期抛出错误,但在我的代码中没有。如果有人可以帮助我,那将非常有帮助。
下面是我的主要课程代码。 `
import org.everit.json.schema.Schema;
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONObject;
import org.json.JSONTokener;
public class TestingJsonSchema {
public static void main(String args[]) {
JSONObject jsonSchema = new JSONObject(
new JSONTokener(TestingJsonSchema.class.getResourceAsStream("/parentSchema.json")));
JSONObject jsonSubject = new JSONObject(
new JSONTokener(TestingJsonSchema.class.getResourceAsStream("/example.json")));
//validateSchema
try{
Schema schemaValidator = SchemaLoader.load((jsonSchema));
schemaValidator.validate(jsonSubject);
}catch (Exception e){
System.out.println(" message is :"+ e.getMessage());
}
}
}
`
下面是我的 pom.xml 文件。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.everit.json</groupId>
<artifactId>org.everit.json.schema</artifactId>
<version>1.5.1</version>
</dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
下面是我的父 json 文件“parentSchema.json”。
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"additionalProperties": false,
"properties": {
"id": {
"enum": ["Russia", "Canada"]
},
"name": {
"type": "string"
},
"price": {
"type": "number"
}
},
"if": {
"properties": { "id": { "const" : "Russia" }}
},
"then": {
"required": ["name"]
},
"else": {
"required": ["price"]
}
}
下面是我要验证的实际 json “example.json”。
{
"id": "Russia",
"price": 10.50
}
它应该给我一个错误,因为我没有发送“名称”,但它正在成功验证,就好像“IF/THEN/ELSE”块从未执行过一样。
【问题讨论】:
标签: java json maven jsonschema json-schema-validator