gpt4 book ai didi

java - 使用 Jackson 反序列化可选多态字段

转载 作者:行者123 更新时间:2023-12-01 19:42:56 25 4
gpt4 key购买 nike

问题

例如,我的购物车中有一些产品的列表,例如电影票、汽车共享和新书。

[
{
"name": "Cinema Ticket"
},
{
"name": "Car Sharing",
"properties": { ... }
},
{
"name": "New Book",
}
]

如您所见,并非所有产品都具有属性注意:该字段是多态的。

问题

我可以使用 Jackson 将“不存在”字段 properties 转换为 null 还是最好更改 api?如果可以的话该怎么做?

jackson 版本:2.10.1

感谢您的解答!

最佳答案

我想你有类似的东西:

public class BaseProduct {
public String name;
}

public class CarSharing extends BaseProduct {
public String properties;
}

public class Book extends BaseProduct {
}

您可以使用 Jackson 多态功能来不显示它,而不是在不存在时将 properties 字段设置为 null。像这样的东西:

@JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = JsonTypeInfo.As.PROPERTY, property = "type")
public class BaseProduct {
public String name;
}

输出将是:

[
{
"type": ".Book",
"name": "Book name"
},
{
"type": ".CarSharing",
"name": "Car share name",
"properties": "a property field"
}
]

关于java - 使用 Jackson 反序列化可选多态字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59156638/

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