Gson: How to change output of Enum
gson, java
Solution
You can use something like this:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapterFactory(new MyEnumAdapterFactory());
or more simply (as Jesse Wilson indicated):
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(RequestStatus.class, new MyEnumTypeAdapter());
and
public class MyEnumAdapterFactory implements TypeAdapterFactory {
@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
Class<? super T> rawType = type.getRawType();
if (rawType == RequestStatus.class) {
return new MyEnumTypeAdapter<T>();
}
return null;
}
public class MyEnumTypeAdapter<T> extends TypeAdapter<T> {
public void write(JsonWriter out, T value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
RequestStatus status = (RequestStatus) value;
// Here write what you want to the JsonWriter.
out.beginObject();
out.name("value");
out.value(status.name());
out.name("code");
out.value(status.getCode());
out.endObject();
}
public T read(JsonReader in) throws IOException {
// Properly deserialize the input (if you use deserialization)
return null;
}
}
}
Problem
I've this enum: ``` enum RequestStatus { OK(200), NOT_FOUND(400); private final int code; RequestStatus(int code) { this.code = code; } public int getCode() { return this.code; } }; ``` and in my Request-class, I have this field: `private RequestStatus status`. When using Gson to convert the Java object to JSON the result is like: ``` "status": "OK" ``` How can I change my GsonBuilder or my Enum object to give me an output like: ``` "status": { "value" : "OK", "code" : 200 } ```