Search code examples
javaspringserializationjacksonjackson2

public property overshadowed by public getter in json serialization


I have this weird scenario - I have this PlatformUser class that implements Principal getName() that returns its email. This is needed for authorization. I would like to be able to serialize and deserialize the PlatformUser based on the public properties name and email. How should I annotate my class for this to work.. As a workaround I had to change the property name to fullName but that defies the purpose of my question. Thanks!

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import javax.persistence.*;
import javax.security.auth.Subject;  
import java.security.Principal;  
import java.util.*;

@Entity
public class PlatformUser implements Principal {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public int id;
    public String name;
    public String email;
    public String role = getUserRole().getRole().toString().toLowerCase();

    @Transient
    private List<GrantedAuthority> authorities;

    public PlatformUser(){}

    public PlatformUser(String email, List<GrantedAuthority> authorities) {
        this.email = email;
        this.authorities = authorities;
    }

    @Override
    public String getName() {
        return email;
    }

    @Override
    public boolean implies(Subject subject) {
        return false;
    }

    public static PlatformUser create(String email, List<GrantedAuthority> authorities) {
        if (StringUtils.isBlank(email)) throw new IllegalArgumentException("Email is blank: " + email);
        return new PlatformUser(email, authorities);
    }

    public Set<GrantedAuthority> getAuthorities() {
        UserRole role = this.getUserRole();
        Set<GrantedAuthority> authorities = new HashSet<>();
        authorities.add(new SimpleGrantedAuthority(role.getRole().authority()));
        return authorities;
    }

    public void setAuthorities(List<GrantedAuthority> authorities) {
        this.authorities = authorities;
    }

    public UserRole getUserRole() {
        return new UserRole(id, Role.ADMIN);

    }

}

Solution

  • I found the answer here: http://www.baeldung.com/jackson-field-serializable-deserializable-or-not

    I added this @Bean in my configuration to ignore getters/setters and use only properties:

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
        mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    
        return mapper;
    }