gpt4 book ai didi

java - 通用树的自定义 Jackson 序列化程序

转载 作者:太空狗 更新时间:2023-10-29 22:47:31 27 4
gpt4 key购买 nike

假设我有一个用 Java 实现的参数化树,如下所示:

public class Tree<E> {
private static class Node {
E element;
List<Node> children.
}

Node root;

//... You get the idea.
}

这里的想法是,上面的实现只关心树的拓扑结构,但对实例化将存储在树中的元素一无所知。

现在,假设我希望我的树元素是地理。它们以树状组织的原因是大陆包含国家,国家包含州或省,等等。为简单起见,地理具有名称和类型:

public class GeoElement { String name; String type; }

因此,最终,地理层次结构如下所示:

public class Geography extends Tree<GeoElement> {}

现在开始 Jackson 连载。假设 Jackson 序列化程序可以看到字段,此实现的直接序列化将如下所示:

{
"root": {
"element": {
"name":"Latin America",
"type":"Continent"
}
"children": [
{
"element": {
"name":"Brazil",
"type":"Country"
},
"children": [
// ... A list of states in Brazil
]
},
{
"element": {
"name":"Argentina",
"type":"Country"
},
"children": [
// ... A list of states in Argentina
]
}
]
}

这种 JSON 呈现并不好,因为它包含来自 Tree 和 Node 类的不必要的工件,即“root”和“element”。我需要的是:

{
"name":"Latin America",
"type":"Continent"
"children": [
{
"name":"Brazil",
"type":"Country"
"children": [
// ... A list of states in Brazil
]
},
{
"name":"Argentina",
"type":"Country"
"children": [
// ... A list of states in Argentina
]
}
]
}

非常感谢任何帮助。 -伊戈尔。

最佳答案

你需要的是@JsonUnwrapped .

Annotation used to indicate that a property should be serialized "unwrapped"; that is, if it would be serialized as JSON Object, its properties are instead included as properties of its containing Object

将此注释添加到 Treeroot 字段和 Node 类的 element 字段,如下所示:

public class Tree<E> {
private static class Node {

@JsonUnwrapped
E element;
List<Node> children.
}

@JsonUnwrapped
Node root;

//... You get the idea.
}

它会给你你想要的输出:

{
"name": "Latin America",
"type": "Continent",
"children": [{
"name": "Brazil",
"type": "Country",
"children": []
}, {
"name": "Argentina",
"type": "Country",
"children": []
}]
}

关于java - 通用树的自定义 Jackson 序列化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14555650/

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