2016-12-11 73 views
0

值我有以下JSON-架構定義三種類型的玩具,要與此json GUI buildergithub)中使用:JSON-模式:基於oneOf

{ 
    "id": "http://some.site.somewhere/entry-schema#", 
    "$schema": "http://json-schema.org/draft-04/schema#", 
    "description": "schema for toys in game", 
    "type": "object", 
    "required": [ "type" ], 
    "properties": { 
     "sawObj": { 
      "type": "object", 
      "oneOf": [ 
       { "$ref": "#/definitions/rect" }, 
       { "$ref": "#/definitions/circle" }, 
       { "$ref": "#/definitions/img" } 
      ] 
     } 
    }, 
    "definitions": { 
     "rect": { 
      "properties": { 
       "width": { "type": "integer" }, 
       "height": { "type": "integer" }, 
       "weight": { "type": "integer" } 
      }, 
      "required": [ "width", "height", "weight" ], 
      "additionalProperties": false 
     }, 
     "circle": { 
      "properties": { 
       "radius": { "type": "integer" }, 
       "weight": { "type": "integer" } 
      }, 
      "required": [ "radius", "weight" ], 
      "additionalProperties": false 
     }, 
     "img": { 
      "properties": { 
       "path": { "type": "string" }, 
       "width": { "type": "integer" }, 
       "height": { "type": "integer" }, 
       "weight": { "type": "integer" } 
      }, 
      "required": [ "path", "width", "height", "weight" ], 
      "additionalProperties": false 
     } 
    } 
} 

如果我挑選例如圓對象我得到一個輸出:

{ 
    "sawObj": { 
    "radius": 0, 
    "weight": 0 
    } 
} 

我想添加一個值「type」,它總是會受到限制,以反映用戶選擇的類型。因此,而不是像這樣:

{ 
    "sawObj": { 
    "type": "circle", 
    "radius": 0, 
    "weight": 0 
    } 
} 

凡型自動由用戶選擇從oneOf屬性部分確定。

我該怎麼用json-schema做到這一點?

回答

0

我能夠做到這一點的枚舉值,只允許一個代表類型的值。我也根據需要設置了類型值,因此它總是自動設置爲'circle'。

"circle": { 
    "properties": { 
     "radius": { 
      "type": "integer" 
     }, 
     "weight": { 
      "type": "integer" 
     }, 
     "type": { 
      "type": "string", 
      "enum": ["circle"] 
     } 
    }, 
    "required": ["radius", "weight", "type"], 
    "additionalProperties": false 
} 

注:我想指出這個解決方案並不理想。我希望找到一個更好的方式來做到這一點。