2015-07-05 70 views
0

在下面的模型中,只有当“detail”数组为空时,才需要“category_id”属性。使用JSON模式对另一个模式验证属性

如果“detail”数组不为空,则不需要“category_id”属性。

我该如何使用JSON模式来做到这一点?

{ 
    "description": "Expense model validation.", 
    "type": "object", 
    "properties": { 
     "description": { 
      "type": "string" 
     }, 
     "category_id": { 
      "type": "string" 
     }, 
     "detail": { 
      "type": "array", 
      "items": { 
       "description": "Expense detail", 
       "type": "object", 
       "properties": { 
        "description": { 
         "type": "string" 
        } 
       }, 
       "required": [ "description" ] 
      } 
     } 
    }, 
    "required": [ "description", "category_id" ] 
} 

回答

1

您可以使用anyOf检查,要么category_id存在,或detail存在,并且至少有一个项目。

{ 
    "description": "Expense model validation.", 
    "type": "object", 
    "properties": { 
    "description": { "type": "string" }, 
    "category_id": { "type": "string" }, 
    "detail": { 
     "type": "array", 
     "items": { 
     "description": "Expense detail", 
     "type": "object", 
     "properties": { 
      "description": { "type": "string" } 
     }, 
     "required": ["description"] 
     } 
    } 
    }, 
    "required": ["description"], 
    "anyOf": [ 
    { "required": ["category_id"] }, 
    { 
     "properties": { 
     "detail": { "minItems": 1 } 
     }, 
     "required": ["detail"] 
    } 
    ] 
} 
+0

使用anyOf,确认只有在这种情况下是成功的: { “说明”: “费用”, “细节”:[{ “描述”: “费用明细” }] } 但这一要求应该是有效的,但没有: { “说明”:“费用”, “CATEGORY_ID”:“555cf4fa5a98e36338886ca6” } 但是我更改为使用oneOf代替anyOf它完美地工作!非常感谢! – Diogo

+0

@Diogo,我没有得到和你一样的结果。你给出的两个例子都为我正确验证。除了'category_id'和'detail'都存在的情况外,'oneOf'应该也可以工作。 'oneOf'要求只有一个(不是两个)模式验证。如果我发布的模式不起作用,那么您使用的验证器可能有问题。 – Jason

+0

你是对的,anyOf工作正常。这是我测试有效负载中的错误。再次! – Diogo