【问题标题】:Returning an array of JSON objects when parsing a schema exception with Everit JSON Schema Validator使用 Everit JSON Schema Validator 解析模式异常时返回 JSON 对象数组
【发布时间】: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);
}

我对@9​​87654323@ 的实现(显然没有抓住重点)是:

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


    【解决方案1】:

    找到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;
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-14
      • 2020-08-07
      • 1970-01-01
      • 2012-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多