8

When using Jackson's JSON schema module, instead of serializing the complete graph I'd like to stop whenever one of my model classes is encountered, and use the class name to insert a $ref for another schema. Can you guide me to the right place in the jackson-module-jsonSchema source to start tinkering?

Here's some code to illustrate the issue:

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"
    }
  }
}
4

3 回答 3

3

这是一个解决问题的自定义 SchemaFactoryWrapper 。不能保证,但它似乎与 Jackson 2.4.3 配合得很好。

更新:从 Jackson 2.5 开始,它变得容易多了。现在您可以指定一个自定义的 VisitorContext

于 2014-07-31T00:22:03.423 回答
2

您可以使用 HyperSchemaFactoryWrapper 而不是 SchemaFactoryWrapper。通过这种方式,您将获得嵌套实体的 urn 参考:

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));
于 2016-05-23T07:31:40.537 回答
0

您可以尝试使用以下代码 -

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

但是您的预期输出无效,它不会说 $ref,除非它至少为“Animals”指定了一次架构。

{
    "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"
        }
    }
}
于 2014-10-15T18:50:39.037 回答