在Java中,向枚举类添加 meta属性是很简单的:
public enum ItemType {
NORMAL("Normal Item", 10, false),
SPECIAL("Special Item", 20, false),
RARE("Rare Item", 30, true);
private final String description;
private final int points;
private final boolean magical;
private ItemType(String description, int points, boolean magical) {
this.description = description;
this.points = points;
this.magical = magical;
}
@Override
public String toString() {
return this.description;
}
public String getDescription() {
return description;
}
public int getPoints() {
return points;
}
public boolean isMagical() {
return magical;
}
}
我希望将这些序列化,但仅在某些rest端点按需进行(即,在枚举名称转换为字符串的情况下,正常的序列化仍应适用:NORMAL
、SPECIAL
或RARE
):
{
"_enum": "NORMAL",
"description": "Normal Item",
"points": 10,
"magical": false
}
有没有什么方法可以注解我的枚举,这样gson或莫希就可以生成这样的json对象?有没有其他的解决方案?
1条答案
按热度按时间4bbkushb1#
我不认为有一个通用的解决方案可以覆盖所有的情况,或者所有的库,但是这将是一个针对gson的解决方案
或者,您可以使用定制的
JsonSerializer
resp.JsonDeserializer
。要使用它,您需要在构建gson对象时将其注册为定制类型适配器。