使用ObjectMapper.convertValue时如何兼容两种JSON结构转换为Parent对象
两种JSON结构兼容转换的调整方案
问题根因
默认配置下的ObjectMapper严格按照POJO的字段层级做映射:
- 第一种JSON存在顶层
child字段,和Parent类定义的Child child字段完全匹配,因此可正常完成转换 - 第二种JSON将
name、surname直接放在顶层,既缺失child嵌套节点,还存在surname字段名前置空格的格式问题,无法匹配Parent类的结构,最终触发IllegalArgumentException转换异常
可选调整方案
方案1:在Parent类增加自定义反序列化逻辑(改动最小,不影响全局配置)
通过@JsonCreator标记静态工厂方法,在方法内主动判断JSON结构,手动完成两种场景的映射,原有转换代码不需要改动即可兼容两种结构:
public class Parent { private Child child; // Jackson反序列化要求的无参构造 public Parent() {} // 引用项目内全局配置好的ObjectMapper实例,避免重复创建 private static final ObjectMapper SHARED_MAPPER = SpringContextUtil.getBean(ObjectMapper.class); @JsonCreator public static Parent parseFromJson(JsonNode node) { Parent parent = new Parent(); // 匹配带child嵌套的第一种结构 if (node.has("child")) { parent.child = SHARED_MAPPER.convertValue(node.get("child"), Child.class); } else { // 匹配平铺的第二种结构,同时兼容带空格的surname字段 Child child = new Child(); child.name = node.get("name").asText(); node.fieldNames().forEachRemaining(field -> { if ("surname".equals(field.trim())) { child.surname = node.get(field).asText(); } }); parent.child = child; } return parent; } // 保留原有getter/setter,不影响业务代码读写 public Child getChild() { return child; } public void setChild(Child child) { this.child = child; } }
方案2:全局配置ObjectMapper的异常处理逻辑,通用适配平铺结构
如果项目内多个类都需要兼容「嵌套结构/平铺结构」两种入参,可以给全局ObjectMapper增加问题处理器,自动将顶层的未知属性映射到内部嵌套对象上:
objectMapper.addHandler(new DeserializationProblemHandler() { @Override public Object handleUnknownProperty(DeserializationContext ctxt, JsonParser p, JsonDeserializer<?> deserializer, Object targetBean, String propertyName) throws IOException { // 仅处理Parent类的转换场景 if (targetBean instanceof Parent parent) { Child child = Optional.ofNullable(parent.getChild()).orElseGet(Child::new); String trimFieldName = propertyName.trim(); // 按字段名映射到Child对象属性 if ("name".equals(trimFieldName)) { child.name = p.getValueAsString(); } if ("surname".equals(trimFieldName)) { child.surname = p.getValueAsString(); } parent.setChild(child); p.skipChildren(); return null; } return super.handleUnknownProperty(ctxt, p, deserializer, targetBean, propertyName); } });
注意:第二种示例JSON中的
" surname": "Finn"字段名带有前置空格,无论选择哪种方案,都需要对字段名做trim处理,否则该字段会被判定为未知属性触发报错。
内容的提问来源于stack exchange,提问作者Dovile Barkauskaite
相关产品推荐
相关产品推荐

