使用 jsonpath 解析数组索引
Parsing with array indices with jsonpath
我有一个 JSON 文件,其中包含许多对象和数组以及数组中的对象。
我在 json 路径 - data.offer.travels[1].routes 中可访问的路由对象中有源和目标之间的路由列表。据说有 15 个这样的路线对象。
在每个路由对象中都有一个名为 legs 的数组,其长度可以是 1、2 或 3。我编写了带有 for 循环的方法以在路由对象和 return 第一个路由索引中循环那只有一条腿。但是它给出了一个错误。
写了一个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
有人可以请教我哪里出错了吗?
您需要使用 jsonPath.param("i",i).get ...
定义参数
这个documentation还有更多例子
我有一个 JSON 文件,其中包含许多对象和数组以及数组中的对象。
我在 json 路径 - data.offer.travels[1].routes 中可访问的路由对象中有源和目标之间的路由列表。据说有 15 个这样的路线对象。
在每个路由对象中都有一个名为 legs 的数组,其长度可以是 1、2 或 3。我编写了带有 for 循环的方法以在路由对象和 return 第一个路由索引中循环那只有一条腿。但是它给出了一个错误。
写了一个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
有人可以请教我哪里出错了吗?
您需要使用 jsonPath.param("i",i).get ...
定义参数
这个documentation还有更多例子