如何将JSON对象绑定到POJO并实现驼峰格式API响应
解决Jackson下划线转驼峰映射问题
问题原因
你之前对@JsonProperty的用法存在误解:@JsonProperty("xxx")是指定字段在**序列化(Java转JSON)和反序列化(JSON转Java)**时对应的JSON字段名。当你给country_code字段标注@JsonProperty("countryCode")时,Jackson会在反序列化时去API返回的JSON中寻找countryCode字段,但实际返回的是country_code,因此无法映射到值,最终输出null;而标注@JsonProperty("country_code")时,序列化和反序列化都使用下划线命名,导致输出不符合驼峰格式要求。
解决方案
方案一:使用@JsonAlias指定反序列化别名(推荐)
修改POJO字段为驼峰命名,用@JsonAlias标注反序列化时可接受的下划线字段名,序列化时自动输出驼峰格式(若字段名本身是驼峰,@JsonProperty可省略):
package com.myapp.flightreservation.model; import com.fasterxml.jackson.annotation.JsonAlias; import lombok.Data; @Data public class AirportInfo { // 反序列化匹配country_code,序列化输出countryCode @JsonAlias("country_code") private String countryCode; // 其他字段同理配置 @JsonAlias("icao") private String icao; @JsonAlias("iata") private String iata; @JsonAlias("name") private String name; @JsonAlias("location") private String location; @JsonAlias("country") private String country; @JsonAlias("longitude") private String longitude; @JsonAlias("latitude") private String latitude; @JsonAlias("link") private String link; @JsonAlias("status") private Integer status; }
方案二:全局配置Jackson自动转换
若所有字段都需要下划线转驼峰,可全局配置ObjectMapper,开启接受下划线命名的特性,无需逐个字段加注解:
- 添加Jackson配置类:
import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class JacksonConfig { @Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); // 开启下划线字段自动映射到驼峰字段 mapper.enable(MapperFeature.ACCEPT_SNAKE_CASE_PROPERTY_NAMES); return mapper; } }
- POJO直接使用驼峰字段:
package com.myapp.flightreservation.model; import lombok.Data; @Data public class AirportInfo { private String countryCode; private String icao; private String iata; private String name; private String location; private String country; private String longitude; private String latitude; private String link; private Integer status; }
方案对比
- 方案一:灵活可控,适合仅部分字段需要转换的场景。
- 方案二:全局生效,减少代码冗余,适合全量字段转换的场景。
内容的提问来源于stack exchange,提问作者Pushpak
相关产品推荐
相关产品推荐

