Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lower case enum Gson

Tags:

java

json

gson

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?

like image 290
user2248702 Avatar asked Mar 15 '15 02:03

user2248702


1 Answers

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();
like image 93
Sotirios Delimanolis Avatar answered Nov 10 '22 10:11

Sotirios Delimanolis