【发布时间】:2017-12-03 08:31:25
【问题描述】:
我目前正在结合使用JSON Schema Validator 和 Gson 来处理异常并验证向 API 发出的 json 请求。
在将请求与架构进行比较时,验证器可以返回多个异常。来自存储库的示例是:
try {
schema.validate(rectangleMultipleFailures);
}
catch (ValidationException e) {
System.out.println(e.getMessage());
e.getCausingExceptions().stream()
.map(ValidationException::getMessage)
.forEach(System.out::println);
}
我对@987654323@ 的实现(显然没有抓住重点)是:
try (InputStream inputStream = this.getClass().getResourceAsStream("SupplierSchemaIncoming.json")) {
JSONObject rawSchema = new JSONObject(new JSONTokener(inputStream));
Schema schema = SchemaLoader.load(rawSchema);
// Throws a ValidationException if requestJson is invalid:
schema.validate(new JSONObject(requestJson));
}
catch (ValidationException ve) {
System.out.println(ve.toJSON().toString());
}
正如您在上面看到的,一种选择是将所有错误作为单个 JSON 返回。
{
"pointerToViolation": "#",
"causingExceptions": [{
"pointerToViolation": "#/name",
"keyword": "type",
"message": "expected type: String, found: Integer"
}, {
"pointerToViolation": "#/type",
"keyword": "type",
"message": "expected type: String, found: Integer"
}],
"message": "2 schema violations found"
}
但是,我不知道如何让异常返回一个 SchemaError 对象数组(如下),我可以根据需要对其进行解析。
package domainObjects;
import com.google.gson.annotations.Expose;
public class SchemaError {
@Expose
String pointerToViolation;
@Expose
String keyword;
@Expose
String message;
public SchemaError() {}
public String getPointerToViolation() {
return pointerToViolation;
}
public void setPointerToViolation(String pointerToViolation) {
this.pointerToViolation = pointerToViolation;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
【问题讨论】:
标签: java arrays json exception jsonschema