gpt4 book ai didi

java - 如何在 JSON 模式 validator 中应用子模式?

转载 作者:太空宇宙 更新时间:2023-11-04 13:39:09 25 4
gpt4 key购买 nike

您好,我正在使用 JSON Schema evaluator在版本 2.2.6 中验证我的服务器响应。这些响应可以包含类型 A、B 或 C 的单个对象,也可以包含复合对象,例如包含 A 对象数组的 D。为了重用每个对象的架构定义,我开始描述同一文件中的所有实体,如here所述。 。现在我的问题是,在验证响应时我必须引用这些单个对象之一。

这是我的(不是)SWE。

JSON 架构文件:

{
"id":"#root",
"properties": {
"objecta": {
"type": "object",
"id":"#objecta",
"properties": {
"attribute1": {"type": "integer"},
"attribute2": {"type": "null"},
},
"required": ["attribute1", "attribute2"]
},
"objectb": {
"type": "object",
"id":"#objectb",
"properties": {
"attribute1": {"type": "integer"},
"attribute2": {
"type": "array",
"items": {
"$ref": "#/objecta"
}
}
}
},
"required": ["attribute1", "attribute2"]
},
}
}

现在我想验证包含对象 B 的服务器响应。为此,我尝试了以下操作:

public class SchemeValidator {

public static void main(String[] args) {

String jsonData = pseudoCodeFileLoad("exampleresponse/objectb.txt");
final File jsonSchemaFile = new File("resources/jsonschemes/completescheme.json");
final URI uri = jsonSchemaFile.toURI();

ProcessingReport report = null;

try {
JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
final JsonSchema schema = factory.getJsonSchema(uri.toString() + "#objectb");
JsonNode data = JsonLoader.fromString(jsonData);
report = schema.validate(data);
} catch (JsonParseException jpex) {
// ... handle parsing errors etc.
}
}
}

问题是方案加载不正确。我要么没有收到错误(即使响应无效),要么收到致命的:非法JsonRef,因为该方案似乎是空的。如何在 Java 代码中使用对象 b 的模式?谢谢!!

最佳答案

看来您的 $ref 不正确。它需要是来自 JSON 架构文件基础的相对引用(请参阅 here )。

所以你的 JSON 模式将变成:

{
"id":"#root",
"properties": {
"objecta": {
"type": "object",
"id":"#objecta",
"properties": {
"attribute1": {"type": "integer"},
"attribute2": {"type": "null"},
},
"required": ["attribute1", "attribute2"]
},
"objectb": {
"type": "object",
"id":"#objectb",
"properties": {
"attribute1": {"type": "integer"},
"attribute2": {
"type": "array",
"items": {
"$ref": "#/properties/objecta"
}
}
}
},
"required": ["attribute1", "attribute2"]
},
}

}

我已将“/properties”添加到您的 $ref 中。它的操作类似于模式文件中对象定义的 XPath。

关于java - 如何在 JSON 模式 validator 中应用子模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31387293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com