问题
I have a senior were I have to validate the schema for below json data.
{
'userId': 123,
'userType': CUSTOMER
}
Information about JSON: Were userId
is an integer and the userType
is enum['Customer','Admin','Guest']
So the issue is that I want to validate the JSON data from the JSON schema based on :
- If
userId
is present thenuserType
is required. - If
userType
['Customer','Admin']
is present but userId is not then it should not validate the JSON data. - But if the
userType
is['Guest']
then their userId is required.
Here I have achieved point 1 but cannot achieve point 2 and 3 :
{
'type': 'object',
'properties': {
'user': {
'type': 'integer',
'minimum': 0
},
'userType': {
'type': 'string',
'enum': ['Customer','Admin','Guest'],
}
},
'dependencies': {
'userId': ['userType']
}
}
Can anyone suggest me json schema solution for this ?
回答1:
I think you can solve it with with the property anyOf of json Schema, you can add multiple schemas to validate if the userType
is Customer
or Admin
force one schema and if the user type is Guest
force another one, like this:
{
"anyOf": [
{
"type": "object",
"properties": {
"user": {
"type": "integer",
"minimum": 0
},
"userType": {
"type": "string",
"enum": [
"Customer",
"Admin"
]
}
}
},
{
"type": "object",
"properties": {
"user": {
"type": "integer",
"minimum": 0
},
"userType": {
"type": "string",
"enum": [
"Guest"
]
},
"userId": {
"type": "string"
}
}
}
]
}
来源:https://stackoverflow.com/questions/59963930/two-way-binding-dependences-based-on-enum-value-in-json-schema