我需要通过Java、Spring Boot项目上的@JsonAlias注释从嵌套对象中获取国家/地区名称。
@JsonAlias 对于 name 字段可以正常工作。但是,这种方法不适用于嵌套或子对象。
@Getter
@Setter
public class Student {
private Long id;
@JsonAlias("fullName")
private String name;
@JsonAlias("presentAddress.country.name")
private String presentAddressCountryName;
@JsonAlias("permanentAddress.country.name")
private String permanentAddressCountryName;
}
String jsonString = """
{
"id": 1,
"fullName": "Md. Badrul Alam",
"presentAddress": {
"id": 1,
"location": "Dhaka",
"country": {
"id": 1,
"name": "Bangladesh"
}
},
"permanentAddress": {
"id": 1,
"location": "Jashore",
"country": {
"id": 1,
"name": "Pakistan"
}
}
}
"""
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Student student = objectMapper.readValue(jsonString, Student.class);
@JsonAlias 设计用于别名字段名称,而不是用于 JSON 对象中的深度嵌套。要处理嵌套属性,您可以将自定义反序列化逻辑与 Jackson 的 @JsonDeserialize 注释和自定义反序列化器结合使用。