问题
例如,我的购物车里有一些产品的清单,比如电影票、汽车共享和新书。
[
{
"name": "Cinema Ticket"
},
{
"name": "Car Sharing",
"properties": { ... }
},
{
"name": "New Book",
}
]如您所见,并不是所有的产品都有properties。注意:这个字段是多态的。
问题
我是否可以使用杰克逊将“不存在”的字段properties转换为null,或者最好更改api?如果我能那么怎么做呢?
杰克逊版本: 2.10.1
谢谢你的回答!
发布于 2019-12-03 12:35:35
我想你有这样的东西:
public class BaseProduct {
public String name;
}
public class CarSharing extends BaseProduct {
public String properties;
}
public class Book extends BaseProduct {
}不需要将属性字段设置为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"
}
]https://stackoverflow.com/questions/59156638
复制相似问题