从java类生成JSON模式 [英] Generate JSON schema from java class
问题描述
我有一个POJO类
public class Stock{
int id;
String name;
Date date;
}
是否有可以将POJO转换为JSON模式的注释或开发框架/ api如下所示
Are there any annotations or development framework/api that can convert POJO to JSON schema like below
{"id":
{
"type" : "int"
},
"name":{
"type" : "string"
}
"date":{
"type" : "Date"
}
}
我还可以扩展架构以添加必需等信息:是,每个字段的描述等,通过在POJO上指定一些注释或配置,并可以生成如下的JSON模式。
and also i can expand the schema to add information like "Required" : "Yes", description for each field, etc., by specifying some annotations or configurations on POJO and can generate JSON Schema like below.
{"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"
}
}
推荐答案
我自己需要这样做,但是需要获得最新的架构规范(截至本文的v4)。我的解决方案是以下链接的第一个答案:
从POJO生成Json模式
I ran into a need to do this myself, but needed to get the latest schema spec (v4 as of this post). My solution is the first answer at the link below: Generate Json Schema from POJO with a twist
使用org.codehaus.jackson.map包中的对象而不是com.fasterxml.jackson .databind包。如果您按照此页面上的说明操作,那么您做错了。只需使用jackson-mapper模块。
Use objects from the org.codehaus.jackson.map package rather than the com.fasterxml.jackson.databind package. If you're following the instructions on this page then you're doing it wrong. Just use the jackson-mapper module instead.
以下是未来googlers的代码:
Here's the code for future googlers:
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);
}
这篇关于从java类生成JSON模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!