Gson:如何改变Enum的输出

dhr*_*hrm 28 java gson

我有这个枚举:

enum RequestStatus {
  OK(200), NOT_FOUND(400);

  private final int code;

  RequestStatus(int code) {
    this.code = code;
  }

  public int getCode() {
    return this.code;
  }
};
Run Code Online (Sandbox Code Playgroud)

在我的Request-class中,我有这个字段:private RequestStatus status.

使用Gson将Java对象转换为JSON时,结果如下:

"status": "OK"
Run Code Online (Sandbox Code Playgroud)

如何更改我的GsonBuilder或我的Enum对象,为我提供如下输出:

"status": {
  "value" : "OK",
  "code" : 200
}
Run Code Online (Sandbox Code Playgroud)

Gui*_*let 19

你可以使用这样的东西:

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapterFactory(new MyEnumAdapterFactory());
Run Code Online (Sandbox Code Playgroud)

或更简单(如杰西威尔逊所说):

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(RequestStatus.class, new MyEnumTypeAdapter());
Run Code Online (Sandbox Code Playgroud)

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;
         }
    }

}
Run Code Online (Sandbox Code Playgroud)