JSON模式中用于多个字段的if-then-else

时间:2019-11-11 17:50:33

标签: json jsonschema json-schema-validator

如何根据条件将几个字段设为“必填”?

例如;在以下情况下,如果状态 ==失败,那么我只需要四个字段(“ orgId”,             “ subunitId”,             “ fundOutType”,             “状态”) 但状态的任何其他值将更改必填字段列表:(“ transactionId”,             “ orgId”,             “ subunitId”,             “ fundOutType”,             “ fundOutAmount”,             “状态”)

我的以下解决方案不起作用。请帮忙。

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "versionId": "1.0",
    "javaInterfaces": [
        "java.io.Serializable"
    ],
    "type": "object",
    "properties": {
        "transactionId": {
            "type": "string"
        },
        "orgId": {
            "type": "string"
        },
        "subunitId": {
            "type": "string"
        },
        "fundOutType": {
            "type": "string"
        },
        "fundOutAmount": {
            "type": "string"
        },
        "status": {
            "type": "string"
        },
        "lang": {
            "type": "string"
        },
        "transactionCreatedDateTime": {
            "type": "integer",
            "format": "date-time"
        },
        "userId": {
            "type": "string"
        }
    },
    "if": {
        "properties": {
            "status": {
                "const": "Failed"
            }
        },
        "required": [ "status" ]
    },
    "then": {
        "required": [
            "orgId",
            "subunitId",
            "fundOutType",
            "status"
        ]
    },
    "else": {
        "required": [
            "transactionId",
            "orgId",
            "subunitId",
            "fundOutType",
            "fundOutAmount",
            "status"
        ]
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用oneOf子句代替if / else:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "versionId": "1.0",
  "javaInterfaces": [
    "java.io.Serializable"
  ],
  "type": "object",
  "properties": {
    "transactionId": {
      "type": "string"
    },
    "orgId": {
      "type": "string"
    },
    "subunitId": {
      "type": "string"
    },
    "fundOutType": {
      "type": "string"
    },
    "fundOutAmount": {
      "type": "string"
    },
    "status": {
      "type": "string"
    },
    "lang": {
      "type": "string"
    },
    "transactionCreatedDateTime": {
      "type": "integer",
      "format": "date-time"
    },
    "userId": {
      "type": "string"
    }
  },
  "oneOf": [
    {
      "properties": {
        "status": {
          "const": "Failed"
        }
      },
      "required": [
        "orgId",
        "subunitId",
        "fundOutType",
        "status"
      ]
    },
    {
      "required": [
        "transactionId",
        "orgId",
        "subunitId",
        "fundOutType",
        "fundOutAmount",
        "status"
      ]
    }
  ]
}

请参阅文档https://json-schema.org/draft/2019-09/json-schema-core.html#rfc.section.9.2.1