2013-10-14 21 views
2

我需要爲包含java Properties對象作爲其屬性之一的對象創建JSON模式。 嵌套的Properties對象將只是key = value的列表。鍵和值都是字符串類型。 我未能找到任何描述如何定義包含2種新類型的模式的文檔。如何爲持有Properties對象的對象定義JSON模式?

要把它是這樣的:

{ 
"type": "object", 
"name": "MyObj", 
"properties": { 
    "prop1": { 
     "type": "string", 
     "description": "prop1", 
     "required": true 
    }, 
    "props": { 
     "type": "array", 
     "items": { 
      "type": "object" 
      "properties": { 
       "key": { 
        "type": "string", 
        "description": "key", 
        "required": true 
       }, 
       "value": { 
        "type": "string", 
        "description": "the value", 
        "required": true 
       } 
      } 
      "description": "the value", 
      "required": true 
     } 
    } 
} 

}

回答

16

你寫的模式(假設逗號是固定的)描述表單的數據:

{ 
    "prop1": "Some string property goes here", 
    "props": [ 
     {"key": "foo", "value": "bar"}, 
     {"key": "foo2", "value": "bar2"}, 
     ... 
    ] 
} 

如果這是你想要的東西,那麼你就已經完成了。

但是,我不知道爲什麼你在數組中使用鍵/值對,而不是使用帶有字符串鍵的JSON對象。使用additionalProperties關鍵字,你可以有一個模式:

{ 
    "type": "object", 
    "name": "MyObj", 
    "properties": { 
     "prop1": { 
      "type": "string", 
      "description": "prop1" 
     }, 
     "props": { 
      "type": "object", 
      "additionalProperties": { 
       "type": "string", 
       "description": "string values" 
      } 
     } 
    } 
} 

這說明像數據格式:

{ 
    "prop1": "Some string property goes here", 
    "props": { 
     "foo": "bar", 
     "foo2": "bar2" 
    } 
} 
+1

如果您想要對該鍵施加約束,則還可以使用patternProperties和additionalProperties:false。您也可以使用「模式」對值強加約束。 – guyarad

0

W3 schools (JSON Syntax)您可以閱讀數組應該如何界定。

沒有類似xsd的模式,但是我找到了一個方法on json-schema.org。如果你能,我會建議你google-GSON library for JSON。你可以存儲密鑰值"id" : "value",並建立了一個對象,包含所有requieed對:

{ "lang" : "EN" , "color" : "red" } 

您發佈的型號爲incorect,您可以檢查它on jsonlint.com 這裏是一個工作版本,我不知道如果正如預期的那樣。

{ 
    "type": "object", 
    "name": "MyObj", 
    "properties": [ 
     { 
      "prop1": { 
       "type": "string", 
       "description": "prop1", 
       "required": true 
      }, 
      "props": { 
       "type": "array", 
       "items": { 
        "type": "object", 
        "properties": { 
         "key": { 
          "type": "string", 
          "description": "key", 
          "required": true 
         }, 
         "value": { 
          "type": "string", 
          "description": "the value", 
          "required": true 
         } 
        }, 
        "description": "the value", 
        "required": true 
       } 
      } 
     } 
    ] 
} 
+0

謝謝,我定人失蹤,很少有逗號,但我想我試圖問是:是否有更常見的方法來定義JSON模式中的java類屬性成員,還是應該留在數組中? – aviad