【发布时间】:2020-07-23 17:33:15
【问题描述】:
有没有办法告诉 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" }。
【问题讨论】:
-
你需要明确调用 toString -
Color.RED.toString() -
@RishikeshDhokare 请看更新示例,枚举实际上嵌套在其他类中。