0

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.

LeO
  • 4,238
  • 4
  • 48
  • 88
  • Check out this answer - https://stackoverflow.com/a/20551381/2143488 – gohil90 Jan 24 '18 at 10:25
  • Thx for the hint - this gave me the leading hint how to resolve it - see below. – LeO Jan 24 '18 at 11:42
  • 0 I'm trying to achieve the same thing, injecting the entityManager in a JsonDeserializer class. I see your code references builder. What field is this, and what does it do? The code is unclear. – BlackBeltBob Jul 09 '20 at 13:39
  • As far as I remember you need to approach it on a general level, i.e. following the answer gives you the possibility that these will be injected. – LeO Jul 09 '20 at 14:09

1 Answers1

0

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!

LeO
  • 4,238
  • 4
  • 48
  • 88