无法反序列化一个简单的枚举

时间:2017-05-18 12:06:43

标签: 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, 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;
    }


    }

但是ObjectMapper无法反序列化UserType枚举

我的Json字符串:

{"password":"135","username":"cooper","accountNonExpired":true,"grantedAuthorities":["ROLE_BROKER"],"userType":"BROKER","brokerName":null,"accountNonLocked":true,"credentialsNonExpired":true,"enabled":true}

这是反序列化的代码:

User user = objectMapper.readValue(jsonString,User.class);

但是在desierializing到User对象之后,这就是用户对象的外观:

{password='135', username='cooper', accountNonExpired=true, accountNonBlocked=true, enabled=true, credentialNonExpired=true, grantedAuthorities=[ROLE_BROKER], userType=null}

如您所见,userType为null。出了什么问题?

1 个答案:

答案 0 :(得分:0)

include = JsonTypeInfo.As.EXISTING_PROPERTY更改为include = JsonTypeInfo.As.PROPERTY后,它才有效。