如何通过Jackson注解从嵌套JSON对象中提取单个字段?
问题描述
我获取到如下JSON对象:
{ "id": "...", "Nested": { "nestedId": "..." } }
顶层对象和Nested对象中都包含大量其他属性,我仅关注顶层对象的十几个字段,以及Nested对象的nestedId。
目前我使用如下Kotlin数据类实现反序列化:
import com.fasterxml.jackson.annotation.* @JsonIgnoreProperties(ignoreUnknown = true) data class MainObject( @JsonProperty("id") val id: String, // ... more properties for other fields @JsonProperty("nested") val nested: Nested?, ) { val nestedId: String? get() = nested?.id } @JsonIgnoreProperties(ignoreUnknown = true) data class Nested( @JsonProperty("id") val id: String )
我可以通过n.nestedId便捷访问嵌套对象的id,但希望移除额外的Nested类。请问如何仅通过注解反序列化嵌套id而非整个对象?我了解自定义JsonDeserializer,但它的代码量和复杂度比额外类更高;也考虑过使用readTree和path,但那样需要手动映射所有其他字段。
解决方案
直接在MainObject中用@JsonProperty指定嵌套字段的完整路径即可,无需定义额外的Nested类。具体做法是把nestedId字段的@JsonProperty值设为"Nested.nestedId"(注意和JSON中实际的键大小写保持一致),同时保留@JsonIgnoreProperties(ignoreUnknown = true)忽略无关属性。
修改后的代码如下:
import com.fasterxml.jackson.annotation.* @JsonIgnoreProperties(ignoreUnknown = true) data class MainObject( @JsonProperty("id") val id: String, // ... 其他需要映射的顶层字段 @JsonProperty("Nested.nestedId") val nestedId: String? )
这样Jackson会自动解析JSON中Nested对象下的nestedId值,直接赋值给MainObject的nestedId属性,既不需要额外嵌套类,也不用手动处理JSON树,其他顶层字段的映射逻辑也能正常保留,代码简洁且满足需求。
内容的提问来源于stack exchange,提问作者Robert
相关产品推荐
相关产品推荐

