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)