我正在使用com.github.fge.jsonschema。使用 Java 工作。
以下是 JSON 架构。
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Employee",
"description": "employee description",
"type": "object",
"properties": {
"eid": {
"description": "The unique identifier for a emp",
"type": "integer"
},
"ename": {
"description": "Name of the emp",
"type": "string"
},
"qual":{
"$ref": "#/definitions/qualification"
}
},
"definitions": {
"qualification":
{
"description": "Qualification",
"type": "string"
}
}
}
这是根据架构进行验证的 JSON。
{
"eid":1000,
"ename": "mrun",
"qualification": "BE"
}
问题是,如果我们传递任何错误的数据,它会正确验证 eid 和 ename 的类型(即整数或字符串)。 例如:
{
"eid":"Mrun", //should be Integer
"ename": 72831287, //should be String
"qualification": 98372489 //should be String
}
如果我们传递错误的类型进行资格验证,那么它就会验证为 true(即,它不会验证资格类型,可能因为它是嵌套的)。
需要对整个 JSON 执行验证。
还有其他解决方案来验证 JSON 中的嵌套对象吗?
提前致谢。
最佳答案
你的例子
{
"eid":"Mrun",
"ename": 72831287,
"qualification": 98372489
}
与您的架构不匹配。您的架构需要像
这样的对象{
"eid": "Mrun",
"ename": 72831287,
"qual": {
"qualification": 98372489
}
}
但是,如果您只想重用“资格”定义,您的架构应该类似于
"properties": {
"eid": {
"description": "The unique identifier for a emp",
"type": "integer"
},
"ename": {
"description": "Name of the emp",
"type": "string"
},
"qualification":{
"$ref": "#/definitions/qualification"
}
}
关于java - 根据 JSON 模式验证 JSON(在 Java 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59769923/