如何使用Jackson修改JSON键名?Spring Boot场景下问题求助
解决Spring Boot中Jackson序列化键名不符合预期的问题
你的问题出在@JsonProperty的使用方式上:当前代码里@JsonProperty("employeeId")会同时控制**反序列化(JSON转对象)和序列化(对象转JSON)**的键名,所以输出时依然会用employeeId而非你期望的id。
要实现「反序列化时接受employeeId/employeeName,序列化时输出id/name」的需求,只需修改实体类的注解,用@JsonAlias指定反序列化的别名,用@JsonProperty指定序列化的目标键名:
package com.poc.entity; import com.fasterxml.jackson.annotation.JsonAlias; import com.fasterxml.jackson.annotation.JsonProperty; public class Employee { @JsonProperty("id") @JsonAlias("employeeId") private Integer id; @JsonProperty("name") @JsonAlias("employeeName") private String name; // 需添加getter/setter,Spring序列化需要访问字段 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
关键说明:
@JsonProperty("id"):指定对象序列化成JSON时,该字段的键名为id@JsonAlias("employeeId"):指定反序列化时,JSON中的employeeId键可映射到该字段- 必须添加字段的getter/setter方法,Spring的Jackson消息转换器需要通过这些方法访问字段内容
修改后,接口返回的JSON会符合预期:{"id":123,"name":"John Smith"}
内容的提问来源于stack exchange,提问作者ram prasad
相关产品推荐
相关产品推荐

