小写枚举Gson

use*_*702 8 java json gson

我需要使用Gson输出枚举值,由于客户端限制需要小写.

例如CLOSE_FILEclose_file.

有一个简单的方法吗?我已经看过制作一个实现的类,JsonSerializer但看起来我必须手动序列化整个类(这是非常复杂的)是这样的吗?

Sot*_*lis 18

如果您可以控制enum类型,请使用其成员注释@SerializedName并为其指定适当的序列化值.例如,

enum Action {
    @SerializedName("close_file")
    CLOSE_FILE;
}
Run Code Online (Sandbox Code Playgroud)

如果您无法控制enum,请TypeAdapter在创建Gson实例时提供自定义.例如,

Gson gson = new GsonBuilder().registerTypeAdapter(Action.class, new TypeAdapter<Action>() {

    @Override
    public void write(JsonWriter out, Action value) throws IOException {
        out.value(value.name().toLowerCase());
    }

    @Override
    public Action read(JsonReader in) throws IOException {
        return Action.valueOf(in.nextString().toUpperCase());
    }
}).create();
Run Code Online (Sandbox Code Playgroud)