如何将嵌套JSON映射为简单Java对象?映射失败求助
解决JSON嵌套结构到扁平Java类的映射问题
没问题,咱们来搞定这个字段全为null的映射问题!你的核心问题是JSON是嵌套结构,但你想直接映射到一个扁平的Java类,而你用的@JsonProperty("information.type")写法在字段上是不生效的——Jackson默认只会在当前层级查找属性名,不会解析这种点分隔的嵌套路径。
下面给你两种实用的解决方案,都能实现把嵌套JSON映射到单个InformationModel类:
方案一:用私有解析方法手动提取字段
这种方法简单直接,不需要额外配置,通过一个私有方法接收整个information对象,然后手动解析里面的嵌套字段:
@JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class InformationModel { private String name; private String lastName; private String type; private String date; // 无参构造函数(Spring StreamListener需要这个来实例化对象) public InformationModel() {} // 用@JsonProperty接收整个information对象,手动解析嵌套字段 @JsonProperty("information") private void unpackInformation(Map<String, Object> information) { this.type = (String) information.get("type"); this.date = (String) information.get("date"); // 解析user子对象 Map<String, Object> user = (Map<String, Object>) information.get("user"); if (user != null) { this.name = (String) user.get("name"); this.lastName = (String) user.get("lastName"); } } // 别忘了添加所有字段的getter和setter public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } }
这种方法的好处是逻辑清晰,不需要依赖Jackson的特殊特性,Spring StreamListener能正常识别并调用这个私有解析方法。
方案二:用@JsonCreator构造函数指定路径
如果你更喜欢用Jackson的注解方式,可以通过带参数的构造函数,配合@JsonProperty指定完整的嵌套路径(Jackson 2.6+支持这种写法):
@JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class InformationModel { private String name; private String lastName; private String type; private String date; // 带参数的构造函数,用@JsonProperty指定每个字段的嵌套路径 @JsonCreator public InformationModel( @JsonProperty("information.type") String type, @JsonProperty("information.date") String date, @JsonProperty("information.user.name") String name, @JsonProperty("information.user.lastName") String lastName) { this.type = type; this.date = date; this.name = name; this.lastName = lastName; } // 必须保留无参构造函数,Spring需要它来处理对象实例化 public InformationModel() {} // getter和setter // ... 同方案一 }
注意事项
- 无论用哪种方案,必须保留无参构造函数——Spring StreamListener在反序列化时需要用它来创建对象实例。
- 确保你的Spring项目中使用的Jackson版本是2.6及以上(方案二需要这个版本支持路径式
@JsonProperty)。 - 如果还是有问题,可以检查Spring的Jackson配置,确保没有禁用相关的反序列化特性。
内容的提问来源于stack exchange,提问作者moffeltje
相关产品推荐
相关产品推荐

