首页 > 解决方案 > 使用 jsonpath 解析数组索引

问题描述

我有一个 JSON 文件,其中包含许多对象和数组以及数组中的对象。

我有一个在 json 路径中可访问的路由对象中的源和目标之间的路由列表 - data.offer.travels[1].routes。据说有 15 个这样的路线对象。

在每个路由对象中都有一个名为legs 的数组,其长度可以是1、2 或3。我编写了一个带有for 循环的方法,在路由对象中循环并返回只有一条腿的第一个路由索引。但它给出了一个错误。

为此编写了一个 for 循环。这是代码

public JSONObject PrepareProvBookingRequestBody() throws IOException, ParseException {

    File jsonExample = new File(System.getProperty("user.dir"),"\\JSONOutputFiles\\ThreeAdults_TwoCh_StdRet_PUB\\ThreeAdults_TwoCh_StdRet_PUB_JS.json");
    JsonPath jsonPath = new JsonPath(jsonExample);
    int routeindexOutbound=0;
    int routeindexInbound=0;
    List<Object> routesOutbound = jsonPath.getList("data.offer.travels[1].routes");
    int NoOfOutboundRoutes= routesOutbound.size();

    for (int i=0; i<NoOfOutboundRoutes; i++)
    {
        JsonArray legs = jsonPath.get("data.offer.travels[1].routes[i].legs");
        int NoOfLegs = legs.size();
        if (NoOfLegs==1) {
        routeindexOutbound=i;
        break;
     }

    }

String DepartureDate = jsonPath.getString("data.offer.travels[1].routes[routeindexOutbound].legs[0].service_schedule_date");

这是我得到的错误

java.lang.IllegalArgumentException: The parameter "i" was used but not 
defined. Define parameters using the JsonPath.params(...) function

有人可以就我在这里出错的地方提出建议吗?

标签: javarest-assuredjsonpath

解决方案


jsonPath.param("i",i).get ... 您需要使用此文档定义参数 以及更多示例


推荐阅读