杰克逊:生成带引用的模式 [英] Jackson: generate schemas with references

查看:235
本文介绍了杰克逊:生成带引用的模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

输出:

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


推荐答案

这是一个自定义SchemaFactoryWrapper 解决了这个问题。没有保证,但它似乎与Jackson 2.4.3相当不错。

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

更新:随着Jackson 2.5的推进,它会变得更加容易。现在,您可以指定自定义VisitorContext

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

这篇关于杰克逊:生成带引用的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆