gpt4 book ai didi

java - Gson:如何更改枚举的输出

转载 作者:IT老高 更新时间:2023-10-28 21:16:06 24 4
gpt4 key购买 nike

我有这个枚举:

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

private final int code;

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

public int getCode() {
return this.code;
}
};

在我的请求类中,我有这个字段:private RequestStatus status

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

"status": "OK"

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

"status": {
"value" : "OK",
"code" : 200
}

最佳答案

你可以这样使用:

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapterFactory(new MyEnumAdapterFactory());

或更简单地说(如 Jesse Wilson 所说):

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(RequestStatus.class, new MyEnumTypeAdapter());

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

}

关于java - Gson:如何更改枚举的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10297264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com