【问题标题】:Can declare your JSON Schema by a reference to type?可以通过对类型的引用来声明您的 JSON 模式吗?
【发布时间】:2017-03-08 23:36:18
【问题描述】:

我正在尝试验证一小部分 JSON,例如:

{
    "success": true,
    "message": "all's good!"
}

适用于架构:

{
    "type": "object",
    "properties": {
        "success": { "type": "boolean" },
        "message": { "type": "string"  }
    }
}

但是它在架构上失败了

{
    "definitions": {
        "response": {
            "type": "object",
            "properties": {
                "success": { "type": "boolean" },
                "message": { "type": "string"  }
            }
        }
    },

    "type": { "$ref": "#/definitions/response" }
}

有错误

java.lang.AssertionError: schema resource:/json-schema/sample.schema.json was > invalid: fatal: JSON Schema 无效,无法继续 语法错误:

[ {
    "level" : "error",
    "message" : "value has incorrect type (found object, expected one of [array, string])",
    "domain" : "syntax",
    "schema" : {
        "loadingURI" : "resource:/json-schema/sample.schema.json#",
        "pointer" : ""
    },
    "keyword" : "type",
    "found" : "object",
    "expected" : [ "array", "string" ]
} ]

级别:“致命”

您是否不允许对定义部分之外的类型使用引用?我的动机是这是对单一案例的回应,但也有这种结构嵌套在其他案例中的案例。

如果重要的话,我使用的是json-schema-validator 2.2.6 版。


PS -这是一个简化的示例,实际架构更复杂,无法证明为什么需要重用而不是复制和粘贴。

【问题讨论】:

  • 我很困惑为什么您将顶级类型声明为定义。你能举一个更完整的例子吗?您可以在属性和属性值之间重用定义。
  • @AdamRosini 我有一个返回响应的调用,但我还有第二个调用,它执行批处理工作,将 1 个 id 的映射返回到响应。我想重用响应声明。为了能够重用定义 AFAIK,它必须在定义中,还是可以在另一个文件中重用非定义类型?

标签: java jsonschema json-schema-validator


【解决方案1】:

您可以使用“id”和“$ref”。

用于识别的id,例如:

{
    "type": "object",
      "id": "#response",
      "properties": {
        "success": { "type": "boolean" },
        "message": { "type": "string"  }
       }
  }
}

然后你使用 $ref,例如:

"some": { "$ref": "#response" }

或外部参考:

"ext": { "$ref": "http://url.com#response" }

http://json-schema.org/latest/json-schema-core.html#anchor27

【讨论】:

    【解决方案2】:

    type 关键字的值必须是 JSON 原始类型之一的名称字符串(例如“字符串”、“数组”等),或这些字符串的数组。这就是错误消息所说的。关键字type 必须是字符串或数组。我认为你正在尝试做的最接近的事情是......

    {
        "definitions": {
            "response": {
                "type": "object",
                "properties": {
                    "success": { "type": "boolean" },
                    "message": { "type": "string"  }
                }
            }
        },
        "allOf": [{ "$ref": "#/definitions/response" }]
    }
    

    【讨论】:

      【解决方案3】:

      您应该在它自己的文件中声明您的定义,并且他们让您的类型引用该文件引用。详情请见How to manage multiple JSON schema files?

      【讨论】:

        猜你喜欢
        • 2021-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-01
        • 2015-06-02
        • 2012-12-25
        相关资源
        最近更新 更多