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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With