java - 使用 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
有人可以就我在这里出错的地方提出建议吗?
解决方案
jsonPath.param("i",i).get ...
您需要使用此文档定义参数 以及更多示例
推荐阅读
- c++ - 为什么 c++ foreach 比简单的单线程循环慢?
- javascript - 从数组中删除在另一个数组中找不到其属性的对象
- java - Spring Security如何将principal注入Controller?
- spring-boot - 在spring boot中一个接一个地调度任务
- java - 两个 Java 字符串相同的值不同的 Eclipse id 不正确 HashMap
- c - PC2 中的运行时错误,但在 Dev-C++ 中有效
- haskell - 使用 >>= 将表达式转换为 do 表示法
- angular - ngIf 在 BSDropdown 上
- javascript - 从 bpmn Moodle 中的异步函数中检索对象
- python - 通过服务更换壁纸的问题