Json 无法反序列化简单枚举
这是我的类用户Json 无法反序列化简单枚举,json,java-8,jackson,Json,Java 8,Jackson,这是我的类用户 @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "userType") @JsonSubTypes({ @JsonSubTypes.Type(value = Broker.class, name = "BROKER"), @JsonSubTypes.Type(value = Admin.class, n
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "userType")
@JsonSubTypes({
@JsonSubTypes.Type(value = Broker.class, name = "BROKER"),
@JsonSubTypes.Type(value = Admin.class, name = "ADMIN")
})
public class User {
protected String password;
@Id
protected String username;
protected boolean accountNonExpired=true, accountNonBlocked=true, enabled=true, credentialNonExpired=true;
protected String[] grantedAuthorities;
protected UserType userType;
public User(){
}
public UserType getUserType() {
return userType;
}
public void setUserType(UserType userType) {
this.userType = userType;
}
@Override
public String toString() {
return "User{" +
"password='" + password + '\'' +
", username='" + username + '\'' +
", accountNonExpired=" + accountNonExpired +
", accountNonBlocked=" + accountNonBlocked +
", enabled=" + enabled +
", credentialNonExpired=" + credentialNonExpired +
", grantedAuthorities=" + Arrays.toString(grantedAuthorities) +
", userType=" + userType +
'}';
}
它使用枚举作为“UserType”类型的字段
public enum UserType {
BROKER("BROKER"),ADMIN("ADMIN");
private static Map<String, UserType> FORMAT_MAP = Stream
.of(UserType.values())
.collect(Collectors.toMap(s -> s.value, Function.identity()));
private final String value;
UserType(String value) {
this.value = value;
}
@JsonCreator
public static UserType fromString(String string) {
return Optional
.ofNullable(FORMAT_MAP.get(string))
.orElseThrow(() -> new IllegalArgumentException(string));
}
@JsonValue
public String getValue(){
return value;
}
}
这是要反序列化的代码:
User user = objectMapper.readValue(jsonString,User.class);
但在对用户对象取消序列化后,用户对象的外观如下所示:
{password='135', username='cooper', accountNonExpired=true, accountNonBlocked=true, enabled=true, credentialNonExpired=true, grantedAuthorities=[ROLE_BROKER], userType=null}
如您所见,userType为null。出了什么问题?在我将
include=JsonTypeInfo.As.EXISTING\u属性更改为include=JsonTypeInfo.As.PROPERTY
后,它就起作用了 如何将UserType
序列化到字符串?您的类中没有相关代码。除此之外,维护一个冗余的value
属性没有任何意义,该属性包含相同的字符串name()
将返回并且UserType.valueOf(string)
接受。没有它,格式映射
也将过时。@Holger:我用一个JsonValue编辑我的UserType类。它仍然不起作用。我在问题中也对其进行了编辑检查反序列化的用户
实例的属性,而不是查看字符串表示形式,这会很有帮助,确定这是反序列化问题还是正在查看的字符串的创建问题。为什么要使用@JsonCreator
显式管理反序列化?您只需要在使用字符串而不是其name()
表示枚举时执行此操作。是的,只要public enum UserType{BROKER,ADMIN}
就可以了。如果您认为需要显式指定的表示,只需使用public enum UserType{@JsonProperty(“BROKER”)BROKER、@JsonProperty(“ADMIN”)ADMIN}
…如前所述,您应该检查/澄清结尾包含UserType=null
的字符串是如何创建的。
{password='135', username='cooper', accountNonExpired=true, accountNonBlocked=true, enabled=true, credentialNonExpired=true, grantedAuthorities=[ROLE_BROKER], userType=null}