我目前正在使用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);
}
我try catch
的实现(很明显错过了):
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;
}
}
答案 0 :(得分:0)
发现another answer,建议将对象从JSONObject序列化为JSONElement并返回该对象。 catch()
现在有:
catch (ValidationException ve) {
JSONObject jsonObject = ve.toJSON();
Gson gson = new Gson();
JsonElement element = gson.fromJson(jsonObject.toString(), JsonElement.class);
return element;
}