从pojo生成JsonSchema:如何添加“description”?自动? [英] Generating JsonSchema from pojo: how do I add "description" automatically?
问题描述
我试图在我的项目中从pojos自动生成JsonSchema:代码如下所示:
I am trying to automatically generate JsonSchema from pojos in my project: The code looks like this:
ObjectMapper mapper = new ObjectMapper();
SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
mapper.acceptJsonFormatVisitor(clazz, visitor);
JsonSchema jsonSchema = visitor.finalSchema();
String schemaString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema);
当clazz定义如下:
When clazz is defined like this:
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"
}
}
}
一切都很棒。我想要做的是将description键添加到模式中,这样我就会看起来像:
All that is great. What I want to do is add the "description" key to the schema, so that I instead have something that looks like:
{
"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类中的字段上,但经过半天的充气后我还没有找到一。这是要走的路吗?或者我需要对我的访客做些什么吗?
I assumed there was some annotation I could just put on the fields in my ZKBean class, but after half a day of futzing I have not found one. Is this the way to go? Or do I need to do something with my Visitor?
谢谢,
Jesse
Thanks, Jesse
推荐答案
您可以使用 @JsonPropertyDescription
注释生成自Jackson 2.4.1以来有效的json模式。下面是一个示例:
You can use the @JsonPropertyDescription
annotation for generating json schema which works since Jackson 2.4.1. Here is an example:
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"
}
}
}
这篇关于从pojo生成JsonSchema:如何添加“description”?自动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!