[英]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.