Spring MVC & custom JsonSerializer

2019-08-25 01:50发布

问题:

I'm using Spring 5.0 with MVC and have a custom (de)serializer for an entity, e.g.

@JsonDeSerialize(using = RoleDeserializer.class)
public class Role implements Serializable { 
....

and for deserializing I have (StdDesializer won't change anything)

public class RoleDeserializer extends JsonDeserializer<Role> {
  EntityManager em;
  public RoleDeserializer(EntityManager em) {
        this.em = em;
  }
....

which gives me always an Exception

MappingJackson2HttpMessageConverter:205 Failed to evaluate Jackson deserialization for type [[simple type, class test.Role]]: c
om.fasterxml.jackson.databind.JsonMappingException: Class test.RoleDeserializer has no default (no arg) constructor

but somehow I need to have that constructor since if I do it like

public class RoleDeserializer extends JsonDeserializer<Role> {
@PersitenceContext
EntityManager em;
 ....

The automatic annotation on em with @PersitenceContext does not work because it is not injected with Spring, i.e. not initialized.

Remark: Following the suggestions I could not resolve the issue. The reason of the behavior is explained in link - but this does not get rid of the Exceptions :-/

Help is greatly appreciated.

回答1:

After the hint to my question I figured out how to resolve this issue in Spring 5.0 (most likely as well in 4.1.1) - without XML:

@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {    
        final HashMap<Class<?>, JsonDeserializer<?>> map = new HashMap<>();
        map.put(Role.class, new RoleDeserializer());
        // more classes could be easily attached the same way...
        builder.deserializersByType(map);

        converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
    }
}

after this the annotations @Autowired or @PersistenceContext work as expected in the classes :-) Thx for the support!