小写枚举Gson [英] Lower case enum Gson
问题描述
我需要使用Gson输出枚举值,因为客户端限制需要小写。
I need to output enum values using Gson which due to client limitations need to be in lower case.
例如 CLOSE_FILE
将是 close_file
。
有一种简单的方法吗?我已经看过制作一个实现 JsonSerializer
的类,但看起来我必须手动序列化整个类(这很复杂)是这样的吗?
Is there a simple way of doing this? I have looked at making a class which implements JsonSerializer
but it looks like I would have to manually serialize the whole class (which is quite complex) is this the case?
推荐答案
如果您可以控制枚举
类型,请使用<$注释其成员c $ c> @SerializedName 并为其指定适当的序列化值。例如,
If you have control over the enum
type, annotate its members with @SerializedName
and give it the appropriate serialized value. For example,
enum Action {
@SerializedName("close_file")
CLOSE_FILE;
}
如果你无法控制枚举
,在创建 Gson
实例时提供自定义 TypeAdapter
。例如,
If you don't have control over the enum
, provide a custom TypeAdapter
when creating a Gson
instance. For example,
Gson gson = new GsonBuilder().registerTypeAdapter(Action.class, new TypeAdapter<Action>() {
@Override
public void write(JsonWriter out, Action value) throws IOException {
out.value(value.name().toLowerCase());
}
@Override
public Action read(JsonReader in) throws IOException {
return Action.valueOf(in.nextString().toUpperCase());
}
}).create();
这篇关于小写枚举Gson的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!