如何在Spring Boot中使用@JsonAlias注解映射嵌套JSON属性?
解决@JsonAlias无法映射嵌套JSON字段的问题
问题原因
@JsonAlias仅支持为当前属性指定同级JSON字段的别名,无法识别presentAddress.country.name这种点分隔的嵌套路径。它会把整个路径当作一个普通的同级字段名,而你的JSON中并没有这个名字的字段,因此无法完成映射。
解决方案
方案1:用@JsonProperty指定嵌套路径
直接替换@JsonAlias为@JsonProperty,Jackson原生支持通过点路径映射嵌套字段:
@Getter @Setter public class Student { private Long id; @JsonAlias("fullName") private String name; @JsonProperty("presentAddress.country.name") private String presentAddressCountryName; @JsonProperty("permanentAddress.country.name") private String permanentAddressCountryName; }
反序列化时,ObjectMapper会自动解析嵌套路径,将对应的值赋值到目标属性。
方案2:结合@JsonAlias与自定义Setter方法
如果需要同时支持嵌套路径和其他字段别名,可以在Setter方法上配置@JsonProperty和@JsonAlias:
@Getter @Setter public class Student { private Long id; @JsonAlias("fullName") private String name; private String presentAddressCountryName; private String permanentAddressCountryName; @JsonAlias({"presentAddress.country.name", "presentCountry"}) @JsonProperty("presentAddress.country.name") public void setPresentAddressCountryName(String name) { this.presentAddressCountryName = name; } @JsonAlias({"permanentAddress.country.name", "permanentCountry"}) @JsonProperty("permanentAddress.country.name") public void setPermanentAddressCountryName(String name) { this.permanentAddressCountryName = name; } }
这种方式既支持嵌套路径映射,也兼容其他字段别名。
方案3:定义完整嵌套实体类(推荐)
如果后续需要操作地址、国家的其他属性,建议遵循面向对象设计,定义完整的嵌套实体结构:
@Getter @Setter public class Student { private Long id; @JsonAlias("fullName") private String name; private Address presentAddress; private Address permanentAddress; } @Getter @Setter public class Address { private Long id; private String location; private Country country; } @Getter @Setter public class Country { private Long id; private String name; }
之后可以通过student.getPresentAddress().getCountry().getName()获取国家名称,这种方式更易扩展和维护。
内容的提问来源于stack exchange,提问作者Badrul
相关产品推荐
相关产品推荐

