繁体   English   中英

根据 JSON 模式验证 JSON(在 Java 中)

[英]Validate JSON against JSON schema (in Java)

我正在使用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
}

如果我们仅通过错误类型进行限定,那么它验证为真(即它不验证限定类型可能是因为它是嵌套的)。

需要对整个 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"   
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM