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

标签 java json validation jsonschema json-schema-validator

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

相关文章:

javascript - 将原型(prototype)附加到 JavaScript 对象

asp.net - 在 asp.net 中,我需要向文本框添加验证器,强制输入为数字

javascript - 将错误消息添加到 javascript 的验证摘要中

java - 线程中的异常处理

java - 如何通过 JsonSystem(Itemscript JSON 库)使用内存数据存储?

java - 如何在Java中快速读取大型JSON文件到ArrayLists

python - '值错误: Image with id {} already added' When Run Evaluation on OpenImage Dataset

java - 内部类甚至可以访问外部类的私有(private)成员..这不是侵犯隐私吗?

java - 比较器compare()方法排序困惑

java - 如何让 Vista 的讲述人将我的 Swing 组件读回给我?