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

如何从Post接口响应体获取指定字段?获取id返回null问题求助

问题分析与解决

核心问题

你的代码存在两个致命错误,导致无法正确获取id:

  1. JSON结构解析错误
    接口返回的是单个JSON对象,但你用JsonPath.from(jsonString).get("")把它当成数组解析成List<Map<String, Object>>,这个List实际是无效结构,循环逻辑根本无法正确执行。

  2. if语句语法错误
    if (...) ; { ... }里的分号会让if的逻辑体变成空语句,后面的代码块不管条件是否满足都会执行,但因为前面的List结构错误,item.get("id")取不到有效数据,最终Id始终为null。

修正后的代码

String jsonString = response.asString();
// 直接解析为单个Map,匹配响应体的单个对象结构
Map<String, Object> body = JsonPath.from(jsonString).get("");
Integer id = null;

// 匹配Fname和Lname后获取id
if (body.get("Fname").toString().equals(Fname) && 
    body.get("Lname").toString().equals(Lname)) {
    id = Integer.parseInt(body.get("id").toString());
}

System.out.println(id);

更严谨的写法(避免空指针)

如果担心接口返回的Fname/Lname可能为null,可以增加非空判断:

String jsonString = response.asString();
Map<String, Object> body = JsonPath.from(jsonString).get("");
Integer id = null;

String respFname = (String) body.get("Fname");
String respLname = (String) body.get("Lname");

if (respFname != null && respFname.equals(Fname) && 
    respLname != null && respLname.equals(Lname)) {
    id = (Integer) body.get("id"); // 直接强转,省去toString再解析的步骤
}

System.out.println(id);

额外说明

如果后续接口可能返回对象数组,那才需要用List<Map<String, Object>>接收。但当前你的响应体是单个对象,直接解析为Map即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 13:00:46