Spring MVC Rest Controller @RequestBody Parsing

时间:2016-02-10 17:49:08

标签: java json spring rest spring-mvc

我有一个弹簧休息网络应用程序,其中包含一个通用的休息控制器,如下所示。在杰克逊将对象序列化为JSON时,GET方法工作正常。但是,当我尝试调用save方法时,RequestBody参数将转换为LinkedHashMap而不是T泛型类型定义的类型。

@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类的属性'version'[java.util.LinkedHashMap]:不能   在后备访问期间查找属性字段!

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, "/*");
    }
}

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:2)

我认为你无法实现自己想要的目标。 Java泛型机制仅在编译时起作用。编译后,通用类型将被删除并替换为实际类型(在您的情况下为Object)。您的控制器无法理解您尝试解析JSON数据的类型。

你得到LinkedHashMap的原因是杰克逊默认使用它是&#34;未知&#34;类型。典型的JSON数据实际上是一个键值映射,Jackson保留了属性排序 - 这就是使用链接哈希映射的原因。