Jackson中使用@JsonProperty后,如何实现实体字段驼峰格式输出?
解决Jackson序列化输出驼峰字段的问题
你当前的问题根源是@JsonProperty("amount_predicted")会同时管控JSON的反序列化(接收数据)和序列化(输出数据)字段名,导致输出仍为下划线格式。这里提供两种实用的解决方法:
方法一:字段级注解拆分读写规则
用@JsonAlias指定反序列化时识别的下划线别名,用@JsonProperty指定序列化时输出的驼峰名称,实现输入输出字段名的分别控制:
public class Amount { @JsonAlias("amount_predicted") // 反序列化时匹配JSON中的下划线字段 @JsonProperty("amountPredicted") // 序列化时输出驼峰格式字段 private BigDecimal amountPredicted; // 必须添加getter和setter,Jackson依赖这些方法访问字段 public BigDecimal getAmountPredicted() { return amountPredicted; } public void setAmountPredicted(BigDecimal amountPredicted) { this.amountPredicted = amountPredicted; } }
方法二:全局配置统一处理(适合多字段场景)
如果项目中有大量类似字段需要处理,全局配置更高效。以Spring Boot为例,创建Jackson配置类分别指定反序列化和序列化的命名策略:
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategies; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class JacksonConfig { @Bean public ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); // 反序列化:将JSON下划线命名转为实体类驼峰字段 objectMapper.setDeserializationConfig( objectMapper.getDeserializationConfig() .with(PropertyNamingStrategies.SNAKE_CASE) ); // 序列化:将实体类驼峰字段转为JSON驼峰输出 objectMapper.setSerializationConfig( objectMapper.getSerializationConfig() .with(PropertyNamingStrategies.LOWER_CAMEL_CASE) ); return objectMapper; } }
此时实体类可简化,无需额外注解:
public class Amount { private BigDecimal amountPredicted; // getter和setter不可省略 public BigDecimal getAmountPredicted() { return amountPredicted; } public void setAmountPredicted(BigDecimal amountPredicted) { this.amountPredicted = amountPredicted; } }
注意:无论使用哪种方法,都要确保字段有对应的getter方法——Jackson默认通过getter方法序列化输出字段,缺少getter会导致该字段无法输出到JSON中。
内容的提问来源于stack exchange,提问作者user1555190
相关产品推荐
相关产品推荐

