I am trying to generate a JSON schema using POJOs with deep inheritance structure.
Using jackson-module-jsonSchema
library I am able to generate a schema.
Given a simplified Java example:
public interface I {...}
public class A implements I {
public int varA;
}
public class B implements I {
public int varB;
}
public class C {
public I varC;
}
Below is my code to generate the schema:
import com.fasterxml.jackson.databind.*
import com.fasterxml.jackson.module.jsonSchema.*
// ...
ObjectMapper mapper = new ObjectMapper();
SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
mapper.acceptJsonFormatVisitor(mapper.constructType(C.class), visitor);
JsonSchema schema = visitor.finalSchema();
String outputSchemaJson = mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(schema);
Actual Json Schema:
{
"type" : "object",
"id" : "urn:jsonschema:com:mycompany:GenerateSchemas:C",
"properties" : {
"varC" : {
"type" : "any"
}
}
}
Desired Json Schema:
{
"definitions": {
"A": {
"type" : "object",
"id" : "urn:jsonschema:com:mycompany:GenerateSchemas:A",
"properties" : {
"varA" : {
"type" : "integer"
}
}
},
"B": {
"type" : "object",
"id" : "urn:jsonschema:com:mycompany:GenerateSchemas:B",
"properties" : {
"varB" : {
"type" : "integer"
}
}
}
},
"type" : "object",
"id" : "urn:jsonschema:com:mycompany:GenerateSchemas:C",
"properties" : {
"varC" : {
"type" : "object",
"oneOf": [
{ "$ref": "urn:jsonschema:com:mycompany:GenerateSchemas:A" },
{ "$ref": "urn:jsonschema:com:mycompany:GenerateSchemas:B" }
]
}
}
}
I have tried overriding core classes from Json Schema library. This answer from stack overflow was helpful to generate a schema with references.
Now I am trying to understand what I need to override such that I can use reflection to get all inheriting-classes of an interface and add oneOf
references to it.