Make Gson to use Enum string value instead of constant name

Viewed 1830

Is there a way to tell Gson to use the string value itself, not its Java constant name? Ideally globally in Gson config, so it would do that for all enums.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class Main {
  public static class Dress {
    public Color color;
  }

  public static enum Color {
    RED("red"),
    BLUE("blue");

    private final String type;
    Color(final String type) { this.type = type; }

    public String toString() { return type; }
  }

  public static void main(String[] args) throws InterruptedException {
    Dress dress = new Dress();
    dress.color = Color.RED;

    GsonBuilder builder = new GsonBuilder();
    builder.setPrettyPrinting();
    Gson gson = builder.create();
    System.out.println(gson.toJson(dress));
    // ==> { "color": "RED" }
  }
}

It prints { "color": "RED" } instead of { "color": "red" }.

2 Answers

Use @SerializedName with serialization value

import com.google.gson.annotations.SerializedName;

public static enum Color {
    @SerializedName("red")
    RED("red"),
    @SerializedName("blue")
    BLUE("blue");
    ...
}

Another way is using a custom serializer

class ColorSerializer implements JsonSerializer {
   @Override
   public JsonElement serialize(Color src, Type typeOfSrc, JsonSerializationContext context) {
      return new JsonPrimitive(src.toString());
   }
}

And register custom serializer in builder

builder.registerTypeAdapter(Color.class, new ColorSerializer());

Create a custom serializer like:

public class EnumSerializer<T extends Enum<T>>
                    implements JsonSerializer<T> {
    @Override
    public JsonElement serialize(T src, Type typeOfSrc,
                JsonSerializationContext context) {
        return new JsonPrimitive(src.toString());
    }
}

Register it like:

builder.registerTypeAdapter(Color.class, new EnumSerializer<>());
// there is a reason for generics: that way you can easily register it to 
// other Enum types also, for example:
// builder.registerTypeAdapter(SomeEnum.class, new EnumSerializer<>());

If you need to apply it to a more than one or all Enum and you do not wish to register it separately to each one you can use TypeAdapterFactory (bit more complicated). First you need the TypeAdapter:

public class EnumTypeAdapter<T extends Enum<T>> extends TypeAdapter<T> {
    @Override
    public void write(JsonWriter out, T value) throws IOException {
        out.jsonValue(value.toString());
    }
    @Override
    public T read(JsonReader in) throws IOException {
        return null;
    }
}

Then the factory:

public static class EnumTypeAdapterFactory implements TypeAdapterFactory {
    @Override
    // Actually it might be easier to just make EnumTypeAdapter non-generic
    // but on the other hand it might be better if used in some other contexts
    // and in some other ways. Thus these suppressions
    @SuppressWarnings({"rawtypes", "unchecked"})
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        // This if applies to all Enums. Change if not wanted.            
        if(Enum.class.isAssignableFrom(type.getRawType())) {
            return new EnumTypeAdapter();
        } else {
            return  null;                
        }
    }
}

and register it:

builder.registerTypeAdapterFactory(new EnumTypeAdapterFactory());
Related