【发布时间】:2021-05-28 18:12:51
【问题描述】:
在 Java 中,向枚举类添加元属性很简单:
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;
}
}
我想这样序列化这些,但只能在某些休息端点按需序列化(即,在枚举名称转换为字符串的情况下,正常序列化仍应适用:NORMAL、SPECIAL 或 @987654324 @):
{
"_enum": "NORMAL",
"description": "Normal Item",
"points": 10,
"magical": false
}
有没有办法注释我的枚举,以便 gson 或 moshi 可以生成这样的 json 对象?有没有其他解决办法?
【问题讨论】: