2014-10-05 90 views
20

我有一個POJO類生成Java類JSON模式

public class Stock{ 
int id; 
String name; 
Date date; 
} 

是否有任何註釋或開發框架/ API,可以POJO轉換成JSON架構如下圖所示

{"id": 
     {    
     "type" : "int" 
     }, 
"name":{ 
     "type" : "string" 
     } 
"date":{ 
     "type" : "Date" 
     } 
} 

而且我可以通過在POJO上指定一些註釋或配置來擴展模式以添加諸如「必需」,「是」,每個字段的描述等的信息,並且可以像下面那樣生成JSON模式。

{"id": 
     {    
     "type" : "int", 
     "Required" : "Yes", 
     "format" : "id must not be greater than 99999", 
     "description" : "id of the stock" 
     }, 
"name":{ 
     "type" : "string", 
     "Required" : "Yes", 
     "format" : "name must not be empty and must be 15-30 characters length", 
     "description" : "name of the stock" 
     } 
"date":{ 
     "type" : "Date", 
     "Required" : "Yes", 
     "format" : "must be in EST format", 
     "description" : "filing date of the stock" 
     } 
} 
+0

這是你在找什麼? http://stackoverflow.com/questions/9593409/convert-pojo-to-json – Elric 2014-10-05 05:01:30

+0

不,將pojo轉換成json對象。我正在尋找生成JSON模式作爲元[關於輸入表單字段映射到pojo字段的信息,如數據類型,是否需要,等等,]給最終用戶)。 – user3587174 2014-10-05 14:23:15

+0

這是一個在線網站,將從json生成json模式:http://www.jsonschema.net/ – DwB 2014-10-06 19:07:57

回答

4

一種這樣的工具是傑克遜JSON架構模塊:

https://github.com/FasterXML/jackson-module-jsonSchema

其使用傑克遜數據綁定的POJO內省遍歷POJO性質,考慮到傑克遜註解,併產生一個JSON模式對象,該對象可能會被序列化爲JSON或用於其他目的。

+0

如果您具有包含需要保留枚舉的枚舉類型的複雜對象,則指定的模塊不起作用。請參閱我的答案以獲取更好的工具(Still Jackson,但是jackson-mapper)。鏈接中的指令導致枚舉在模式中呈現爲簡單字符串 – StormeHawke 2015-01-13 01:51:50

+0

是的,我看到了一個錯誤報告。我希望我們能爲該模塊提供更多的貢獻者 - 這是外部貢獻,相當廣泛地使用,但目前還沒有專門的擁有者。 – StaxMan 2015-01-13 21:55:24

14

我遇到了需要自己做這個,但需要獲取最新的模式規範(v4作爲這篇文章)。我的解決方案是以下鏈接中的第一個答案: Generate Json Schema from POJO with a twist

使用org.codehaus.jackson.map包中的對象而不是com.fasterxml.jackson.databind包。如果您按照this頁面上的說明操作,那麼您做錯了。只需使用jackson-mapper模塊。

下面是未來的Google代碼:

private static String getJsonSchema(Class clazz) throws IOException { 
    org.codehaus.jackson.map.ObjectMapper mapper = new ObjectMapper(); 
    //There are other configuration options you can set. This is the one I needed. 
    mapper.configure(SerializationConfig.Feature.WRITE_ENUMS_USING_TO_STRING, true); 

    JsonSchema schema = mapper.generateJsonSchema(clazz); 

    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema); 
} 
+0

FWIW使用外部模塊進行這項工作會很好,因爲內置生成機制已被棄用(至少這是計劃)。相反,沒有任何技術阻礙讓它在那裏工作。但在此之前很高興知道有一個解決辦法。 – StaxMan 2015-01-13 21:56:27

+0

@StaxMan,因爲你似乎對此有所瞭解,你可以看看這個,告訴我你是否有任何線索?謝謝! http://stackoverflow.com/questions/7161638/how-do-i-use-a-custom-serializer-with-jackson/22108535#22108535 – StormeHawke 2015-01-13 21:58:03

+0

我會看看我是否可以幫助 - 謝謝你報告這個&道歉的事情不工作,因爲他們應該。 – StaxMan 2015-01-13 21:58:56