gson 将具有属性的Java枚举序列化为json对象

jobtbby3  于 2022-11-06  发布在  Java
关注(0)|答案(1)|浏览(185)

在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端点按需进行(即,在枚举名称转换为字符串的情况下,正常的序列化仍应适用:NORMALSPECIALRARE):

{
   "_enum": "NORMAL",
   "description": "Normal Item",
   "points": 10,
   "magical": false
}

有没有什么方法可以注解我的枚举,这样gson或莫希就可以生成这样的json对象?有没有其他的解决方案?

4bbkushb

4bbkushb1#

我不认为有一个通用的解决方案可以覆盖所有的情况,或者所有的库,但是这将是一个针对gson的解决方案

class ItemTypeAdapter extends TypeAdapter<ItemType> {

    private final String ENUM_ID = "_enum";

    @Override
    public void write(JsonWriter writer, ItemType itemType) throws IOException {
        writer.beginObject();
        writer.name(ENUM_ID).value(itemType.name());
        writer.name("description").value(itemType.getDescription());
        writer.name("points").value(itemType.getPoints());
        writer.name("magical").value(itemType.isMagical());
        writer.endObject();
    }

    @Override
    public ItemType read(JsonReader reader) throws IOException {
        String itemType = null;
        reader.beginObject();
        while (reader.hasNext()) {
            String name = reader.nextName();
            if (name.equals(ENUM_ID)) {
                itemType = reader.nextString();
            } else {
                reader.skipValue();
            }
        }
        reader.endObject();
        if (itemType != null) {
            return ItemType.valueOf(itemType);
        } else {
            throw new JsonParseException("Missing '" + ENUM_ID + "' value");
        }
    }
}

或者,您可以使用定制的JsonSerializer resp. JsonDeserializer。要使用它,您需要在构建gson对象时将其注册为定制类型适配器。

相关问题