gpt4 book ai didi

java - 使 Gson 使用枚举字符串值而不是常量名称

转载 作者:行者123 更新时间:2023-12-04 09:23:35 26 4
gpt4 key购买 nike

有没有办法告诉 Gson 使用字符串值本身,而不是它的 Java 常量名称?
理想情况下,在 Gson 配置中是全局的,因此它会为所有枚举执行此操作。

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class Main {
public static class Dress {
public Color color;
}

public static enum Color {
RED("red"),
BLUE("blue");

private final String type;
Color(final String type) { this.type = type; }

public String toString() { return type; }
}

public static void main(String[] args) throws InterruptedException {
Dress dress = new Dress();
dress.color = Color.RED;

GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
Gson gson = builder.create();
System.out.println(gson.toJson(dress));
// ==> { "color": "RED" }
}
}
它打印 { "color": "RED" }而不是 { "color": "red" } .

最佳答案

使用 @SerializedName带序列化值

import com.google.gson.annotations.SerializedName;

public static enum Color {
@SerializedName("red")
RED("red"),
@SerializedName("blue")
BLUE("blue");
...
}

另一种方法是使用自定义序列化程序
class ColorSerializer implements JsonSerializer {
@Override
public JsonElement serialize(Color src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.toString());
}
}
并在构建器中注册自定义序列化程序
builder.registerTypeAdapter(Color.class, new ColorSerializer());

关于java - 使 Gson 使用枚举字符串值而不是常量名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63059972/

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