使用Lombok的@Data和@NoArgsConstructor时Jackson序列化失败问题排查
刚接触Lombok遇到这个问题太正常了,我当初也踩过类似的坑😉。咱们先拆解一下问题:你用了@Data注解,按道理Lombok会自动生成getter/setter,但Jackson却提示找不到GetAllCustomersResponseElement的序列化器,手动写getter就正常,这说明Lombok生成的getter要么没生效,要么Jackson没识别到。下面是几个最可能的原因和解决办法:
1. 最常见的原因:Lombok注解处理器没正确配置
很多时候不是Lombok的锅,是你的IDE或者构建工具(Maven/Gradle)没开启注解处理,导致@Data根本没生成getter/setter,相当于你的类还是只有私有字段,Jackson自然无法序列化。
检查Maven配置
确保你的pom.xml里不仅加了Lombok依赖,还配置了注解处理器路径:
<!-- Lombok依赖 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.30</version> <scope>provided</scope> </dependency> <!-- 配置编译插件的注解处理器 --> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.11.0</version> <configuration> <source>17</source> <!-- 换成你的JDK版本 --> <target>17</target> <annotationProcessorPaths> <path> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.30</version> </path> </annotationProcessorPaths> </configuration> </plugin> </plugins> </build>
检查Gradle配置
dependencies { compileOnly 'org.projectlombok:lombok:1.18.30' annotationProcessor 'org.projectlombok:lombok:1.18.30' } // 如果是Kotlin DSL dependencies { compileOnly("org.projectlombok:lombok:1.18.30") annotationProcessor("org.projectlombok:lombok:1.18.30") }
检查IDE配置
- IntelliJ IDEA:
- 先安装Lombok插件(Settings → Plugins → 搜索Lombok安装)
- 开启注解处理:Settings → Build, Execution, Deployment → Compiler → Annotation Processors → 勾选
Enable annotation processing
- Eclipse:
- 安装Lombok插件(官网下载Lombok.jar,双击安装到Eclipse)
- 开启注解处理:Preferences → Java → Compiler → Annotation Processing → 勾选
Enable annotation processing
验证Lombok是否生效的方法:编译项目后,查看GetAllCustomersResponseElement.class文件,看是否有getId()、getName()这些getter方法,如果有,说明Lombok生效了。
2. @JsonValue注解的冲突问题
你在GetAllCustomersResponse的customers字段上加了@JsonValue注解,这个注解的作用是让Jackson把整个对象序列化为该字段的值(也就是直接返回列表,而不是包含customers字段的JSON对象)。但如果Jackson处理这个列表时,尝试直接访问私有字段而不是通过getter,就可能出问题。
解决办法:
- 把
@JsonValue移到Lombok生成的getter方法上(可以手动写这个方法,Lombok不会覆盖):@Data @NoArgsConstructor public class GetAllCustomersResponse { private List<GetAllCustomersResponseElement> customers = new ArrayList<>(); @JsonValue public List<GetAllCustomersResponseElement> getCustomers() { return customers; } public void addElement(GetAllCustomersResponseElement element) { this.customers.add(element); } } - 或者直接去掉
@JsonValue,让Jackson默认序列化整个对象(返回{"customers": [...]}格式的JSON),看看是否还会报错。
3. Jackson与Lombok版本兼容性问题
某些旧版本的Jackson和Lombok存在适配bug,比如Jackson 2.10之前的版本和Lombok 1.18.x的组合可能会出现无法识别Lombok生成的getter的情况。
建议升级到较新的兼容版本:
- Jackson版本:2.15.x或更高
- Lombok版本:1.18.30或更高
临时应急方案(不推荐长期使用)
如果只是想快速验证问题,可以在Jackson配置中禁用FAIL_ON_EMPTY_BEANS特性,这样即使没有getter,Jackson也不会抛出异常,但这只是绕过问题,不是根本解决办法:
ObjectMapper objectMapper = new ObjectMapper(); objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
内容的提问来源于stack exchange,提问作者Matheus

