rest-assured的JsonPath使用方法总结

JsonPath对于解析Json格式的数据来说非常简单,比如有下面这样的Json数据:

 1 {"lotto":{
 2     "lottoId":5,
 3     "winning-numbers":[2,45,34,23,7,5,3],
 4     "winners":[{
 5       "winnerId":23,
 6       "numbers":[2,45,34,23,3,5]
 7     },{
 8       "winnerId":54,
 9       "numbers":[52,3,12,11,18,22]
10     }]
11   }
12 }

下面是一些简单的使用实例:

 1 //这里的lottoJson代表了上面所说的json数据
 2 JsonPath jsonPath = new JsonPath(lottoJson);
 3 
 4 // 获取lottoId
 5 int lottoId = jsonPath.getInt("lotto.lottoId");
 6 
 7 // 获取winning-numbers列表
 8 List<string> winningNumbers = jsonPath.get("lotto.winning-numbers");
 9 
10 // 下面的语句会返回一个list,list中包含23,54
11 List<integer> winningNumbers = jsonPath.get("lotto.winners.winnerId");

从上面的例子中可以看到所有的获取路径中我们都重复使用了lotto,为了避免这个问题,我们可以设置一个根路径(root path):

 1  //这里lottoJson代表上面的json数据
 2  JsonPath jsonPath = new JsonPath(lottoJson);
 3  //设置根路径
 4  jsonPath.setRoot("lotto");
 5 
 6 // 获取lottoId
 7  int lottoId = jsonPath.getInt("lottoId");
 8 
 9 //获取winning-numbers列表
10 List<string> winningNumbers = jsonPath.get("winning-numbers");
11 
12 // 下面的语句将返回一个list,list中包含23,54
13 List<integer> winningNumbers = jsonPath.get("lotto.winners.winnerId");

如果你只是对提取一个单一的值感兴趣,你还可以这样做:

1 // "from"是从JsonPath中静态导入的
2 int lottoId = from(lottoJson).getInt("lotto.lottoId");

你也可以做一些复杂的操作,比如求winners.numbers的和:

1 int sumOfWinningNumbers = from(lottoJson).
2                            getInt("lotto.winning-numbers.sum()");

或者是找出所有大于10并且winnerId=23的number:

1 // 返回结果是包含45,34 and 23的list
2 List<integer> numbers = from(lottoJson).getList(
3   "lotto.winners.find {it.winnerId == 23}.numbers.findAll {it > 10}",
4    Integer.class);
原文地址:https://www.cnblogs.com/lwjnicole/p/8269965.html