Spring MVC&自定义JsonSerializer [英] Spring MVC & custom JsonSerializer

查看:203
本文介绍了Spring MVC&自定义JsonSerializer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有MVC的Spring 5.0并为实体提供自定义(de)序列化程序,例如

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 { 
....

和反序列化我有(StdDesializer不会改变任何东西)

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;
  }
....

这给了我一个例外

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;
 ....

em上的自动注释 with @PersitenceContext 不起作用,因为它没有用Spring注入,即没有初始化。

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

备注:在建议之后,我无法解决此问题。 link <中解释了此行为的原因/ a> - 但这并没有摆脱异常: - /

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 :-/

非常感谢帮助。

推荐答案

在提示我的问题之后,我想出了如何在Spring 5.0中解决这个问题(最有可能在4.1.1中) - 没有XML:

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()));
    }
}

此后注释 @自动装配的 @PersistenceContext 在课程中按预期工作:-)
Thx for the support!

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

这篇关于Spring MVC&amp;自定义JsonSerializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆