Gson: How to change output of Enum

前端 未结 2 2020
無奈伤痛
無奈伤痛 2020-12-24 13:14

I\'ve this enum:

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

  private final int code;

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

         


        
2条回答
  •  借酒劲吻你
    2020-12-24 14:05

    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  TypeAdapter create(final Gson gson, final TypeToken type) {
                Class rawType = type.getRawType();
                if (rawType == RequestStatus.class) {
                    return new MyEnumTypeAdapter();
                }
                return null;
        }
    
        public class MyEnumTypeAdapter extends TypeAdapter {
    
             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;
             }
        }
    
    }
    

提交回复
热议问题