Lower case enum Gson

六月ゝ 毕业季﹏ 提交于 2020-01-02 02:03:06

问题


I need to output enum values using Gson which due to client limitations need to be in lower case.

For example CLOSE_FILE would be close_file.

Is there a simple way of doing this? I have looked at making a class which implements JsonSerializer but it looks like I would have to manually serialize the whole class (which is quite complex) is this the case?


回答1:


If you have control over the enum type, annotate its members with @SerializedName and give it the appropriate serialized value. For example,

enum Action {
    @SerializedName("close_file")
    CLOSE_FILE;
}

If you don't have control over the enum, provide a custom TypeAdapter when creating a Gson instance. For example,

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();


来源:https://stackoverflow.com/questions/29056676/lower-case-enum-gson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!