Jackson: generate schemes with links

When using the Jackson JSON schema module instead of serializing the full graph, which I would like to stop when one of my model classes meets, and use the class name to insert $ ref for the other schema. Can you direct me to the right place in the jackson-module-jsonSchema source to start messing around?

Here is the code to illustrate the problem:

public static class Zoo { public String name; public List<Animal> animals; } public static class Animal { public String species; } public static void main(String[] args) throws Exception { SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); ObjectMapper mapper = objectMapperFactory.getMapper(); mapper.acceptJsonFormatVisitor(mapper.constructType(Zoo.class), visitor); JsonSchema jsonSchema = visitor.finalSchema(); System.out.println(mapper.writeValueAsString(jsonSchema)); } 

Output:

 { "type" : "object", "properties" : { "animals" : { "type" : "array", "items" : { "type" : "object", "properties" : { <---- Animal schema is inlined :-( "species" : { "type" : "string" } } } }, "name" : { "type" : "string" } } } 

DESIRED Output:

 { "type" : "object", "properties" : { "animals" : { "type" : "array", "items" : { "$ref" : "#Animal" <---- Reference to another schema :-) } }, "name" : { "type" : "string" } } } 
+6
source share
3 answers

Here's a custom SchemaFactoryWrapper that solves the problem. No guarantees, but it seems to work well with Jackson 2.4.3.

UPDATE: With Jackson 2.5, this is much easier. Now you can specify a custom VisitorContext .

+2
source

You can use HyperSchemaFactoryWrapper instead of SchemaFactoryWrapper. Thus, you will receive a link to the urn for nested objects:

 HyperSchemaFactoryWrapper visitor= new HyperSchemaFactoryWrapper(); ObjectMapper mapper = objectMapperFactory.getMapper(); mapper.acceptJsonFormatVisitor(mapper.constructType(Zoo.class), visitor); JsonSchema jsonSchema = visitor.finalSchema(); System.out.println(mapper.writeValueAsString(jsonSchema)); 
+2
source

You can try using the following code -

  ObjectMapper MAPPER = new ObjectMapper(); SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); JsonSchemaGenerator generator = new JsonSchemaGenerator(MAPPER); JsonSchema jsonSchema = generator.generateSchema(MyBean.class); System.out.println(MAPPER.writeValueAsString(jsonSchema)); 

But your expected result is invalid, it will not indicate $ ref, unless it has defined a schema for "Animals" at least once.

 { "type": "object", "id": "urn:jsonschema:com:tibco:tea:agent:Zoo", "properties": { "animals": { "type": "array", "items": { "type": "object", "id": "urn:jsonschema:com:tibco:tea:agent:Animal", "properties": { "species": { "type": "string" } } } }, "name": { "type": "string" } } } 
0
source

Source: https://habr.com/ru/post/955156/


All Articles