是否可能:在Jackson库中序列化/反序列化期间,在类中有一个字段,但它有不同的名称?
例如,我有"Coordiantes"课程.
class Coordinates{
int red;
}
Run Code Online (Sandbox Code Playgroud)
对于来自JSON的反序列化,希望具有如下格式:
{
"red":12
}
Run Code Online (Sandbox Code Playgroud)
但是当我将序列化对象时,结果应该是这样的:
{
"r":12
}
Run Code Online (Sandbox Code Playgroud)
我尝试通过@JsonProperty在getter和setter上应用注释来实现它(具有不同的值):
class Coordiantes{
int red;
@JsonProperty("r")
public byte getRed() {
return red;
}
@JsonProperty("red")
public void setRed(byte red) {
this.red = red;
}
}
Run Code Online (Sandbox Code Playgroud)
但我有一个例外:
org.codehaus.jackson.map.exc.UnrecognizedPropertyException:无法识别的字段"red"
我正在使用Spring Boot(1.2.1),其方式与构建RESTful Web服务教程的方式类似:
@RestController
public class EventController {
@RequestMapping("/events/all")
EventList events() {
return proxyService.getAllEvents();
}
}
Run Code Online (Sandbox Code Playgroud)
所以上面,Spring MVC暗中使用Jackson将我的EventList对象序列化为JSON.
但我想对JSON格式进行一些简单的自定义,例如:
setSerializationInclusion(JsonInclude.Include.NON_NULL)
Run Code Online (Sandbox Code Playgroud)
问题是,自定义隐式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. …Run Code Online (Sandbox Code Playgroud)