作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
有没有办法告诉 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/
我是一名优秀的程序员,十分优秀!