如何自定义Spring Boot隐式使用的Jackson JSON映射器?
2022-08-31 08:59:43
我正在使用Spring Boot(1.2.1),其方式与他们的Building a RESTful Web Service教程类似:
@RestController
public class EventController {
@RequestMapping("/events/all")
EventList events() {
return proxyService.getAllEvents();
}
}
所以在上面,Spring MVC隐式使用Jackson将我的对象序列化为JSON。EventList
但我想对JSON格式进行一些简单的自定义,例如:
setSerializationInclusion(JsonInclude.Include.NON_NULL)
问题是,自定义隐式 JSON 映射器的最简单方法是什么?
我在这篇博客文章中尝试了这种方法,创建了一个CustomObjectMapper等等,但是步骤3“在Spring上下文中注册类”失败了:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'jacksonFix': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire method: public void com.acme.project.JacksonFix.setAnnotationMethodHandlerAdapter(org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter);
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter]
found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
看起来这些说明是针对旧版本的Spring MVC的,而我正在寻找一种简单的方法来使其与最新的Spring Boot配合使用。