Hi is it possible to change name of ENUM in Java? For example, I have enum -
您好可以在Java中更改ENUM的名称吗?例如,我有枚举 -
public enum CloudType {
AZURE, OPENSTACK
}
And a class -
一堂课 -
public class Env{
private CloudType cloudType;
}
And during JACKSON parsing, if I give -
在JACKSON解析期间,如果我给 -
{
"cloudType":"AZURE"
}
Or
{
"cloudType":"azure"
}
It will give me an Env
object with cloudType=AZURE
?
它会给我一个cloudType = AZURE的Env对象?
One thread is there (Jackson databind enum case insensitive), but really we need to do this much? Or
有一个线程(Jackson databind枚举不区分大小写),但我们真的需要这么做吗?要么
@XmlEnumValue("azure")
AZURE("azure"),
will be enough?
会够的吗?
1 个解决方案
#1
1
You can decouple the Java names of the enum
instances from their JSON representations.
您可以将枚举实例的Java名称与其JSON表示分离。
You should add a @JsonValue
-annotated method to your enum CloudType
to tell Jackson which value to use when reading/writing JSON. For that you also need a constructor to initialize this value.
您应该在枚举CloudType中添加@JsonValue注释方法,以告知Jackson在读/写JSON时使用哪个值。为此,您还需要一个构造函数来初始化此值。
Like this:
public enum CloudType {
AZURE("azure"),
OPENSTACK("openstack");
private final String value;
private CloudType(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}
Then Jackson will serialize CloudType.AZURE
to "azure"
,
and deserialize "azure"
to CloudType.AZURE
.
然后Jackson将序列化CloudType.AZURE为“azure”,并将“azure”反序列化为CloudType.AZURE。
#1
1
You can decouple the Java names of the enum
instances from their JSON representations.
您可以将枚举实例的Java名称与其JSON表示分离。
You should add a @JsonValue
-annotated method to your enum CloudType
to tell Jackson which value to use when reading/writing JSON. For that you also need a constructor to initialize this value.
您应该在枚举CloudType中添加@JsonValue注释方法,以告知Jackson在读/写JSON时使用哪个值。为此,您还需要一个构造函数来初始化此值。
Like this:
public enum CloudType {
AZURE("azure"),
OPENSTACK("openstack");
private final String value;
private CloudType(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}
Then Jackson will serialize CloudType.AZURE
to "azure"
,
and deserialize "azure"
to CloudType.AZURE
.
然后Jackson将序列化CloudType.AZURE为“azure”,并将“azure”反序列化为CloudType.AZURE。