JsonPath解析json
JsonPath 能够简化 JSON 数据的查询和操作。
现在有一段json,为了实现查找指定的某个在多个嵌套节点里面的字段内容,
需要用到setRootPath()来重新定位根节点。
以下是源码(示例依赖json-path-5.2.0.jar)
import io.restassured.path.json.JsonPath;
import java.text.ParseException;
import java.util.List;
/**
* @author: wenwan4e
* @Date: 2022/9/6 9:44
*/
public class JsonPathTest {
public static void main(String[] args0) throws ParseException {
JsonPath jsonPath = new JsonPath("[{\n" +
"\t\"id\": 1535478,\n" +
"\t\"expirationDate\": 1773110221000,\n" +
"\t\"customerId\": 222207,\n" +
"\t\"sapQuoteNumber\": \"0002607181\",\n" +
"\t\"subcriptions\": [{\n" +
"\t\t\"id\": 1207295,\n" +
"\t\t\"createdDate\": 1741660621000,\n" +
"\t\t\"dateLastUpd\": 1741660701000,\n" +
"\t\t\"sapInstallNumber\": \"0010260770\",\n" +
"\t\t\"lineItems\": [{\n" +
"\t\t\t\"id\": 296837,\n" +
"\t\t\t\"productSku\": \"MCS2043N\"\n" +
"\t\t}]\n" +
"\t}],\n" +
"\t\"customer\": {\n" +
"\t\t\"id\": 222207\n" +
"\t}\n" +
"}]");
List lineItems = jsonPath.getList("subcriptions.lineItems.id");
System.out.println(lineItems.get(0).toString());
Object produckSku = jsonPath.getList("subcriptions[0].lineItems[0].productSku");
System.out.println(produckSku);
List subcriptionsList = jsonPath.getList("subcriptions");
for (int i = 0; i < subcriptionsList.size(); i++) {
System.out.println(subcriptionsList.get(i));
JsonPath subscription = jsonPath.setRootPath(String.format("subcriptions[%d]", i));
if (subscription.get("lineItems[0].productSku").equals(produckSku)) {
System.out.println(subscription.getString("sapInstallNumber"));
}
}
}
}
控制台输出
> Task :JsonPathTest.main()
[[296837]]
[MCS2043N]
[{id=1207295, createdDate=1741660621000, dateLastUpd=1741660701000, sapInstallNumber=0010260770, lineItems=[{id=296837, productSku=MCS2043N}]}]
[0010260770]

浙公网安备 33010602011771号