[JSON中多个字段的if-then-else

问题描述 投票:0回答:1

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

例如;在以下情况下,如果status == Failed,那么我只需要四个字段(“ orgId”,“ subunitId”,“ fundOutType”,“状态”)但status的任何其他值将更改必填字段列表:(“ 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"
        ]
    }
}
json jsonschema json-schema-validator
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.