![](/img/trans.png)
[英]How to generate the JSONSchema for the JAXB/Moxy annotated POJO class
[英]How to generate JsonSchema As Array from Java Class
我使用fastxml.jackson从Java class生成JsonSchema。 生成的 Jsonschema 如下
{
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
}
}
}
我生成 JsonSchema 的代码
public static String getJsonSchema(Class definitionClass) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper().disable(
MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS);
JavaType javaType = mapper.getTypeFactory().constructType(definitionClass);
JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(mapper);
JsonSchema schema = schemaGen.generateSchema(javaType);
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);
}
我尝试使用ArraySchema arraySchema = schema.asArraySchema();
但它会生成无效的架构。 我预期的 JsonSchema 应该如下所示
{
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
}
}
}
}
TL;DR:调用getJsonSchema(MyClass[].class)
如果我们简单地告诉它生成 Java 数组的模式,则工作正常。
为了演示,我创建了一个符合所示架构的MyClass
class。 为了简化演示,我使用了public
字段,但在现实生活中我们会使用private
字段和public
getter/setter 方法。
class MyClass {
public String id;
public String name;
}
现在,为了表明我们得到与问题相同的结果,我们使用MyClass.class
调用它:
System.out.println(getJsonSchema(MyClass.class));
Output
{
"type" : "object",
"id" : "urn:jsonschema:MyClass",
"properties" : {
"id" : {
"type" : "string"
},
"name" : {
"type" : "string"
}
}
}
现在,我们希望架构是一个数组,所以我们将改为使用MyClass[].class
来调用它。
System.out.println(getJsonSchema(MyClass[].class));
Output
{
"type" : "array",
"items" : {
"type" : "object",
"id" : "urn:jsonschema:MyClass",
"properties" : {
"id" : {
"type" : "string"
},
"name" : {
"type" : "string"
}
}
}
}
以上是使用jackson-module-jsonSchema-2.10.3.jar
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.