我试图在我的项目中从pojos自动生成JsonSchema:代码如下所示:
ObjectMapper mapper = new ObjectMapper();
SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
mapper.acceptJsonFormatVisitor(clazz, visitor);
JsonSchema jsonSchema = visitor.finalSchema();
String schemaString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema);
当clazz定义如下:
public class ZKBean
{
public String anExample;
public int anInt;
}
I end up with this:
{
"type" : "object",
"id" : "urn:jsonschema:com:emc:dpad:util:ZKBean",
"properties" : {
"anInt" : {
"type" : "integer"
},
"anExample" : {
"type" : "string"
}
}
}
一切都很棒。我想要做的是添加"描述"模式的关键,所以我有一些看起来像:
{
"type" : "object",
"id" : "urn:jsonschema:com:emc:dpad:util:ZKBean",
"properties" : {
"anInt" : {
"type" : "integer",
"description" : "Represents the number of foos in the system"
},
"anExample" : {
"type" : "string",
"description" : "Some descriptive description goes here"
}
}
}
我假设有一些注释我可以放在我的ZKBean类中的字段上,但经过半天的充实,我还没找到一个。这是要走的路吗?或者我需要对我的访客做些什么吗?
谢谢, 杰西
答案 0 :(得分:5)
您可以使用@JsonPropertyDescription
注释生成自Jackson 2.4.1以来有效的json模式。这是一个例子:
public class JacksonSchema {
public static class ZKBean {
@JsonPropertyDescription("This is a property description")
public String anExample;
public int anInt;
}
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
mapper.acceptJsonFormatVisitor(ZKBean.class, visitor);
JsonSchema jsonSchema = visitor.finalSchema();
System.out.println(mapper
.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema));
}
}
输出:
{
"type" : "object",
"id" : "urn:jsonschema:stackoverflow:JacksonSchema:ZKBean",
"properties" : {
"anExample" : {
"type" : "string",
"description" : "This is a property description"
},
"anInt" : {
"type" : "integer"
}
}
}
答案 1 :(得分:0)
看来问题不在于jackson库,而是在我用来生成类对象的包中。我的代码粘贴在下面;我怀疑Reflections对象正在删除注释信息(当我手动指定ZKBean.class时,会出现描述)。谢谢你的帮助!
Reflections reflections = new Reflections(
new ConfigurationBuilder().setUrls(
ClasspathHelper.forClassLoader(urlcl)).
addClassLoader(urlcl));
Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(JsonBean.class);
ObjectMapper mapper = new ObjectMapper();
SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
for (Class<?> clazz : annotated)
{
try
{
mapper.acceptJsonFormatVisitor(mapper.constructType(SampleBean.class), visitor);
JsonSchema jsonSchema = visitor.finalSchema();
String schemaString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema);
System.out.println(schemaString);
答案 2 :(得分:0)
我遇到了同样的问题,并确定了另一个可能的原因(只是希望这可能有助于某人)。
我还使用自定义ClassLoader加载Class对象(带有Jackson注释的DTO POJO),并由ObjectMapper和SchemaFactoryWrapper处理它们以生成相应的JSON模式。在我的情况下,我忘了将Jackson-annotations jar添加到ClassLoader,这导致了所描述的问题。