gpt4 book ai didi

java - Jackson:生成带有引用的模式

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:30:24 25 4
gpt4 key购买 nike

当使用 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"
}
}
}

最佳答案

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

更新:从 Jackson 2.5 开始,这就容易多了。现在您可以指定 custom VisitorContext .

关于java - Jackson:生成带有引用的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19149685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com