You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Jackson(JsonNode)解析JSON嵌套路径遇到问题求助

问题描述

尝试用Jackson解析JSON时遇到嵌套字段获取失败的问题,代码如下:

final JsonNode root = objectMapper.readTree(res.payload().asUtf8String());
JsonNode body = root.path("body");
JsonNode message = root.path("body").path("errorMessage");
logger.log(Level.INFO, body.asText());
logger.log(Level.INFO, message.asText());

预期输出:

INFO: {"errorMessage": "input is not a string"}
INFO: "input is not a string"

实际输出:

INFO: {"errorMessage": "input is not a string"}
INFO: 

需要排查为何无法正确获取嵌套的errorMessage值。

问题排查与解决

原因分析

从body.asText()的输出能看出来,root.path("body")返回的是字符串类型的JsonNode(TextNode),而非嵌套的JSON对象(ObjectNode)。也就是说原始JSON里的body字段值是被序列化后的JSON字符串,不是直接的嵌套对象。这种情况下直接用path("errorMessage")访问,自然找不到对应子节点,返回空值。

解决方法

需要先把body的字符串内容重新解析为JsonNode,再获取errorMessage字段,修改后的代码如下:

final JsonNode root = objectMapper.readTree(res.payload().asUtf8String());
JsonNode bodyNode = objectMapper.readTree(root.path("body").asText()); // 重新解析body字符串为JsonNode
JsonNode message = bodyNode.path("errorMessage");
logger.log(Level.INFO, root.path("body").asText());
logger.log(Level.INFO, message.asText());

也可以先判断body的类型,兼容两种情况:

final JsonNode root = objectMapper.readTree(res.payload().asUtf8String());
JsonNode body = root.path("body");
JsonNode message;
if (body.isTextual()) {
    JsonNode bodyNode = objectMapper.readTree(body.asText());
    message = bodyNode.path("errorMessage");
} else {
    message = body.path("errorMessage");
}
logger.log(Level.INFO, body.asText());
logger.log(Level.INFO, message.asText());

这样就能正确获取到errorMessage的值了。

内容的提问来源于stack exchange,提问作者Dreessan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 19:01:13