除了 Polet 的回答,如果你需要一个通用的 Enum 序列化器,你可以通过反射来实现:
public class EnumAdapterFactory implements TypeAdapterFactory
{
@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type)
{
Class<? super T> rawType = type.getRawType();
if (rawType.isEnum())
{
return new EnumTypeAdapter<T>();
}
return null;
}
public class EnumTypeAdapter<T> extends TypeAdapter<T>
{
@Override
public void write(JsonWriter out, T value) throws IOException
{
if (value == null || !value.getClass().isEnum())
{
out.nullValue();
return;
}
try
{
out.beginObject();
out.name("value");
out.value(value.toString());
Arrays.stream(Introspector.getBeanInfo(value.getClass()).getPropertyDescriptors())
.filter(pd -> pd.getReadMethod() != null && !"class".equals(pd.getName()) && !"declaringClass".equals(pd.getName()))
.forEach(pd -> {
try
{
out.name(pd.getName());
out.value(String.valueOf(pd.getReadMethod().invoke(value)));
} catch (IllegalAccessException | InvocationTargetException | IOException e)
{
e.printStackTrace();
}
});
out.endObject();
} catch (IntrospectionException e)
{
e.printStackTrace();
}
}
public T read(JsonReader in) throws IOException
{
// Properly deserialize the input (if you use deserialization)
return null;
}
}
}
用法:
@Test
public void testEnumGsonSerialization()
{
List<ReportTypes> testEnums = Arrays.asList(YourEnum.VALUE1, YourEnum.VALUE2);
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapterFactory(new EnumAdapterFactory());
Gson gson = builder.create();
System.out.println(gson.toJson(reportTypes));
}