Spring MVC Rest Controller @RequestBody解析 [英] Spring MVC Rest Controller @RequestBody Parsing

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

问题描述

我有一个spring rest网络应用程序,其中包含如下所示的通用rest控制器.杰克逊将对象序列化为JSON后,GET方法运行良好.但是,当我尝试调用save方法时,RequestBody参数将转换为LinkedHashMap,而不是T泛型类型定义的类型.

I have a spring rest web app that contains a a generic rest controller like below. The GET methods are working fine having Jackson serializing the objects to JSON. However when I try to call the save method, the RequestBody parameter is being converted to LinkedHashMap instead of the type defined by the T generic type.

@RestController
public abstract class CrudAPI<T extends Object, ID extends Serializable>{

    @Transactional
    @RequestMapping(method = RequestMethod.POST, consumes = "application/json")
    public ResponseEntity<Void> save(@RequestBody T entity){
        service.save(entity);
        return new ResponseEntity(HttpStatus.CREATED);
    }

}

JSON:

{
   "id":null,
   "version":null,
   "name":"Copel",
   "disabled":false,
   "type":"P",
   "labels":[
      {
         "id":null,
         "version":null,
         "name":"unidade consumidora"
      }
   ]
}

我收到以下错误:

HTTP状态500-请求处理失败;嵌套的异常是 org.springframework.beans.NotReadablePropertyException:无效 Bean类[java.util.LinkedHashMap]的属性版本":无法 在后备访问期间查找属性的字段!

HTTP Status 500 - Request processing failed; nested exception is org.springframework.beans.NotReadablePropertyException: Invalid property 'version' of bean class [java.util.LinkedHashMap]: Could not find field for property during fallback access!

Spring配置:

@Configuration
@Import(Application.class)
@EnableWebMvc
@ComponentScan(basePackages = {"br.com.doc2cloud"})
public class WebConfig extends WebMvcConfigurerAdapter implements WebApplicationInitializer {

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    private MappingJackson2HttpMessageConverter jacksonConverter() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new Hibernate5Module());
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        mapper.setDateFormat(new ISO8601DateFormat());
        mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
        mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter();
        jacksonConverter.setObjectMapper(mapper);

        return jacksonConverter;
    }

 @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(jacksonConverter());
        super.configureMessageConverters(converters);
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        servletContext.setInitParameter("javax.servlet.jsp.jstl.fmt.localizationContext", "messages");
        EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD);
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);
        FilterRegistration.Dynamic characterEncoding = servletContext.addFilter("characterEncoding", characterEncodingFilter);
        characterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
    }
}

我的代码有什么问题?

推荐答案

您正在使用哪个版本的Jackson?我升级到2.7.3,并且在使用泛型时(我具有具有保存,列出等通用逻辑的基本控制器)时,我遇到了相同的问题.回滚到2.6.5允许我继续使用通用基类.我尚未研究此问题的原因,但回滚为我解决了该问题.

Which version of Jackson are you using? I upgraded to 2.7.3 and when using generics (I have a base controller with common logic for saving, listing, etc) I had the same issue. Rolling back to 2.6.5 allowed me to continue using my generic base class. I haven't yet researched the reason for the issue but rolling back fixed it for me.

这篇关于Spring MVC Rest Controller @RequestBody解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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