杰克逊:生成带引用的模式

时间:2013-10-03 02:08:34

标签: java json jackson jsonschema

当使用Jackson的JSON模式模块时,我不想在遇到我的某个模型类时停止完整的图形序列,而是使用类名为另一个模式插入$ ref。你能指导我到jackson-module-jsonSchema来源的正确位置开始修修补补吗?

以下是一些代码来说明问题:

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

输出:

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

渴望输出:

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

3 个答案:

答案 0 :(得分:2)

这里有一个解决问题的custom SchemaFactoryWrapper。没有保证,但它似乎与杰克逊2.4.3很好地合作。

更新:随着Jackson 2.5的推进,它变得更加轻松。现在,您可以指定custom VisitorContext

答案 1 :(得分: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));

答案 2 :(得分: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"
        }
    }
}