Jackson: generate schemas with references

空扰寡人 提交于 2019-12-01 17:27:00

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

UPDATE: With Jackson 2.5 onward it's a lot easier. Now you can specify a custom VisitorContext.

You can use the HyperSchemaFactoryWrapper instead of SchemaFactoryWrapper. In this way you will get urn reference for nested entities:

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));

You can try and use 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 output is not valid, it won't say $ref, unless it has specified the 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"
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!