jackson deserialize object with list of spring's interface

后端 未结 1 392
[愿得一人]
[愿得一人] 2020-12-19 08:40

I need to save and load objects from redis.

The object contains list of GrantedAuthority (among other things) which is an interface:

public class Use         


        
相关标签:
1条回答
  • 2020-12-19 09:20

    I think you need to add a custom deserializer

    public class UserAccountAuthenticationSerializer extends JsonDeserializer<UserAccountAuthentication> {
    
    @Override
    public UserAccountAuthentication deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
            throws IOException {
    
        UserAccountAuthentication userAccountAuthentication = new UserAccountAuthentication();
    
        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);
        userAccountAuthentication.setAuthenticated(node.get("authenticated").booleanValue());
    
        Iterator<JsonNode> elements = node.get("authorities").elements();
        while (elements.hasNext()) {
            JsonNode next = elements.next();
            JsonNode authority = next.get("authority");
            userAccountAuthentication.getAuthorities().add(new SimpleGrantedAuthority(authority.asText()));
        }
        return userAccountAuthentication;
    }
    

    }

    This is my json

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

    Then at the top of your POJO

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

    Here's the test

    @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);
    

    }

    0 讨论(0)
提交回复
热议问题