如何在RestAssured(Java)中从API响应的JSON数组获取键值
如何用JsonPath提取JSON数组内的字段值
问题背景
API响应的JSON结构如下:
{ "Code": [ { "id": "string1", "istrue": false, "Text": "hdjdjkdk123" } ] }
现有Java代码尝试用JsonPath提取字段,但路径有误:
String resp = response.asString(); JsonPath js = new JsonPath(resp); js.get("ciext").toString();
需要实现提取id或Text(推测你提到的ciText是笔误)字段值的操作。
解决方案
JsonPath的路径必须与JSON结构严格对应,以下是正确的提取方式:
1. 提取数组第一个元素的id值
String resp = response.asString(); JsonPath js = new JsonPath(resp); // 访问Code数组的第一个元素,提取id字段 String idValue = js.get("Code[0].id");
2. 提取数组第一个元素的Text值
String resp = response.asString(); JsonPath js = new JsonPath(resp); // 访问Code数组的第一个元素,提取Text字段 String textValue = js.get("Code[0].Text");
3. 提取数组所有元素的id值(若数组包含多个元素)
如果Code数组有多个对象,可一次性获取所有id的列表:
String resp = response.asString(); JsonPath js = new JsonPath(resp); List<String> allIds = js.get("Code.id");
关键说明
- 顶层JSON键是
Code,而非你代码中的ciext,这是路径错误的核心原因 - 使用
[索引]访问数组中的指定元素,[0]代表第一个元素 - 在元素路径后直接追加字段名,即可提取对应的值
内容的提问来源于stack exchange,提问作者Adil Raza
相关产品推荐
相关产品推荐

