2017-06-14 83 views
0

我在JSON中有一组两个互不相关的参数组,它们是互斥的。关于哪个参数组应保留在JSON文件中的决定由另一个参数驱动。在JSON中设计互斥参数组

我不确定是否应该通过使用这个特定的结构来处理这个问题,或者实际上它是否属于最佳实践。

在第一种情况下,我们有一个类型为Fixed的合同,其中有两个特定的参数fixedEndfixedEndUnit

在第二种情况下,我们有一个Variable类型的合同,它只有一个特定的参数variableEnd

合同只能是Fixed或Variable。而且,这两种合约类型都有共同的值foobarbaz

我应该如何架构我的JSON

首例

"contract":[ 
     { 
     "type":"Fixed", 
     "fixedEnd":12, 
     "fixedEndUnit":"Months", 
     "foo":"foo", 
     "bar":"bar", 
     "baz":"baz" 
     }] 

第二种情况

"contract":[ 
     { 
     "type":"Variable", 
     "variableEnd":"2012-03-19T07:22Z", 
     "foo":"foo", 
     "bar":"bar", 
     "baz":"baz" 
     }] 

回答

0

解决的办法是增加一个oneOf为每种类型的合同,并内的两组required值:

"agreement": { 
    "items": { 
     "additionalProperties": true, 
     "id": "/properties/contract/items/properties/agreement", 
     "properties": { 
      "type": { 
       "id": "/properties/contract/items/properties/discounts/type", 
       "type": "string", 
       "pattern": "£(\\d+\\.)?\\d" 
      }, 
      "fixedEnd": { 
       "id": "/properties/contract/items/properties/discounts/fixedEnd", 
       "type": "string", 
       "pattern": "6" 
      }, 
      "fixedValue": { 
       "id": "/properties/contract/items/properties/discounts/fixedValue", 
       "type": "string", 
       "pattern": "kWh" 
      }, 
      "variableEnd": { 
       "id": "/properties/contract/items/properties/discounts/variableEnd", 
       "type": "string", 
       "pattern": "6" 
      } 
     }, 
     "oneOf": [{ 
       "required": ["type", "fixedend", "fixedValue"] 
      }, 
      { 
       "required": ["type", "variableEnd"] 
      } 
     ] 
    } 
}