Reputation: 21
I'm generating JsonSchema from Java class using fasterxml.jackson. The generated Jsonschema will be as below
{
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
}
}
}
My code to generate 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);
}
I tried to use ArraySchema arraySchema = schema.asArraySchema();
but it generates invalid schema.
My expected JsonSchema should be like below
{
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
}
}
}
}
Upvotes: 1
Views: 457
Reputation: 159165
TL;DR: Call getJsonSchema(MyClass[].class)
Works fine if we simply tell it to generate the schema of a Java array.
To demo, I created a MyClass
class fitting the shown schema. I used public
fields for simplicity of the demo, but we'd use private
fields and public
getter/setter methods in real life.
class MyClass {
public String id;
public String name;
}
Now, to show that we get the same result as in the question, we call it with MyClass.class
:
System.out.println(getJsonSchema(MyClass.class));
Output
{
"type" : "object",
"id" : "urn:jsonschema:MyClass",
"properties" : {
"id" : {
"type" : "string"
},
"name" : {
"type" : "string"
}
}
}
Now, we want the schema to be an array of those, so we will instead call it using 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"
}
}
}
}
The above was tested using jackson-module-jsonSchema-2.10.3.jar
.
Upvotes: 1