jackson使用spring接口列表反序列化对象

时间:2016-03-01 13:49:00

标签: java spring redis jackson

我需要从redis中保存和加载对象。

该对象包含GrantedAuthority(以及其他内容)的列表,它是一个接口:

public class UserAccountAuthentication implements Authentication {
    private List<GrantedAuthority> authorities;
    private boolean authenticated = true;
    ...
}

杰克逊成功序列化了该对象,但未能将其反序列化,但有以下异常:

abstract types can only be instantiated with additional type information

我知道我可以通过添加:

来指定类型
@JsonTypeInfo(

但是在这种情况下我无法做到,因为GrantedAuthority是Spring的一个接口,我无法改变它。

序列化的json是:

{
"authorities": [
    {
        "authority": "ROLE_NORMAL_USER"
    }
],
"authenticated": true,
"securityToken": {
    "expiration": 1458635906853,
    "token": "sxKi3Pddfewl2rgpatVE7KiSR5qGmhpGl0spiHUTLAAW8zuoLFE0VLFYcfk72VLnli66fcVmb8aK9qFavyix3bOwgp1DRGtGacPI",
    "roles": [
        "ROLE_NORMAL_USER"
    ],
    "expired": false,
    "expirationDateFormatted": "2016-03-22 08:38:26.853 UTC"
},
"name": "admin",
"expired": false

}

摘要GrantedAuthority仅填充SimpleGrantedAuthority

所以我试过了:

objectMapper.registerSubtypes(SimpleGrantedAuthority.class);

但仍然没有运气。

1 个答案:

答案 0 :(得分:5)

我认为您需要添加自定义反序列化器

{"authenticated":true,"authorities":[{"authority":"role1"},{"authority":"role2"}],"details":null,"principal":null,"credentials":null,"name":null}

}

这是我的json

@JsonDeserialize(using = UserAccountAuthenticationSerializer.class)
public class UserAccountAuthentication  implements Authentication {

然后在POJO的顶部

@Test
public void test1() throws IOException {

UserAccountAuthentication userAccountAuthentication = new UserAccountAuthentication();
userAccountAuthentication.setAuthenticated(true);
userAccountAuthentication.getAuthorities().add(new SimpleGrantedAuthority("role1"));
userAccountAuthentication.getAuthorities().add(new SimpleGrantedAuthority("role2"));

String json1 = new ObjectMapper().writeValueAsString(userAccountAuthentication);
UserAccountAuthentication readValue = new ObjectMapper().readValue(json1, UserAccountAuthentication.class);
String json2 = new ObjectMapper().writeValueAsString(readValue);
assertEquals(json1, json2);

这是测试

{{1}}

}