gpt4 book ai didi

java - 如何用 jackson 反序列化空字符串?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:26:52 38 4
gpt4 key购买 nike

我想用 Jackson 反序列化一个 json,我想将空字符串映射到标准枚举类型。

当我尝试将 JsonProperty 与空字符串一起使用时,它会忽略空值并抛出异常;

value not one of declared Enum instance names:......,STANDARD,...

有什么办法可以解决这个问题吗?

public enum Type{

@JsonProperty("")
STANDARD,

@JsonProperty("complex")
COMPLEX,

....

}

我的json;

....
"type": "",
....

最佳答案

@JsonValue会成功的:

public enum Type {

STANDARD(""),
COMPLEX("complex");

private String value;

StatusType(String value) {
this.value = value;
}

@JsonValue
public String getValue() {
return value;
}
}

引用@JsonValue中的相关部分文档:

Marker annotation that indicates that the value of annotated accessor (either field or "getter" method [a method with non-void return type, no args]) is to be used as the single value to serialize for the instance, instead of the usual method of collecting properties of value. [...]

At most one accessor of a Class can be annotated with this annotation; if more than one is found, an exception may be thrown. [...]

NOTE: when use for Java enums, one additional feature is that value returned by annotated method is also considered to be the value to deserialize from, not just JSON String to serialize as. This is possible since set of Enum values is constant and it is possible to define mapping, but can not be done in general for POJO types; as such, this is not used for POJO deserialization.

关于java - 如何用 jackson 反序列化空字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50251828/

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