【问题标题】:JSON schema for payloads accepted vs objects returned接受的有效负载与返回的对象的 JSON 模式
【发布时间】:2016-04-18 18:39:19
【问题描述】:

我正在充实 RESTful Web 服务的模式,但在一件小事上我有点难过。想象一下,如果我有以下架构:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "required": ["name"],
  "properties": {
    "name": {
      "type": "string"
    },
    "urn": {
      "type": "string"
    }
  }
}

由于 URN 是由我的服务生成的,我不想在客户端请求中接受它。所以urn 不包含在required 数组中。但是,响应中需要它,因此我不能使用此模式来验证我的服务给出的响应。我宁愿不必使用两种不同的模式,而必须使它们保持同步。

有没有办法使用单一模式来严格建模这两种情况?或者,如果我需要使用两个架构,有没有办法引用一个通用的结构架构,然后从我的请求和响应架构中覆盖 required 字段?

【问题讨论】:

    标签: json jsonschema


    【解决方案1】:

    这是一个已知问题,没有很好的处理方法。

    将其保留在一个架构中的唯一方法是不在 required 数组中包含服务器生成的属性,并在服务器端进行额外检查以验证这些属性。

    不,没有办法覆盖架构关键字。 JSON Schema 关键字总是向集合添加约束。您需要从通用架构开始,然后使用allOf 进行扩展。

    这是您需要做的事情的示例。

    创建架构:

    {
      "$schema": "http://json-schema.org/draft-04/schema#",
      "id": "http://example.com/create-my-schema",
      "type": "object",
      "required": ["name"]
      "properties": {
        "name": {
          "type": "string"
        }
      }
    }
    

    完整架构:

    {
      "$schema": "http://json-schema.org/draft-04/schema#",
      "id": "http://example.com/my-schema",
      "allOf": [{ "$ref": "http://example.com/create-my-schema" }],
      "required": ["urn"],
      "properties": {
        "urn": {
          "type": "string"
        }
      }
    }
    

    如果您不关心模式的人类可读性,这种方法很好。否则,有些人选择在服务器端动态构建模式,因此生成的模式可能有重复,但代码没有。

    【讨论】:

    • 当然,这并不理想,但我认为我可以使用它。谢谢!
    【解决方案2】:

    您可以通过“oneOf”使用动态架构

    {
        "type" : "object",
        "required" : ["name"],
        "properties" : {
            "name" : {
                "oneOf" : [{
                        "$ref" : "#/definitions/withURN"
                    }, {
                        "$ref" : "#/definitions/withoutURN"
                    }
                ]
            }
        },
        "definitions" : {
            "withURN" : {
                "properties" : {
                    "name" : {
                        "type" : "string"
                    },
                    "urn" : {
                        "type" : "string"
                    }
                }
            },
            "withoutURN" : {
                "properties" : {
                    "name" : {
                        "type" : "string"
                    }
                }
            }
        }
    }
    

    举个例子看看:http://json-schema.org/example2.html

    还有这个讨论帖:How to use dependencies in JSON schema (draft-04)

    【讨论】:

    • 这看起来会在任何情况下验证{"name": "foo", "urn": "bar"},这不是我想要的;只需使用具有这两个属性的模式就可以做到这一点。我想要两个仅在 required 字段的值上有所不同的架构,而不必复制/粘贴这两个架构。
    猜你喜欢
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多