Jsonpath Object parsing JSON-formatted data is very simple, such as the following JSON data:
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]Ten }] One } A}
Here are some simple examples of usage:
1 //the Lottojson here represents the JSON data described above .2JsonPath JsonPath =NewJsonPath (Lottojson);3 4 //Get Lottoid5 intLottoid = Jsonpath.getint ("Lotto.lottoid");6 7 //Get winning-numbers list8list<string> winningnumbers = Jsonpath.get ("Lotto.winning-numbers");9 Ten //The following statement returns a list,list that contains the 23,54 Onelist<integer> winningnumbers = Jsonpath.get ("Lotto.winners.winnerId");
From the example above, we can see that we have reused the lotto in all the fetch paths, in order to avoid this problem, we can set a root path:
1 //here Lottojson represents the JSON data above2JsonPath JsonPath =NewJsonPath (Lottojson);3 //Setting the root path4Jsonpath.setroot ("Lotto");5 6 //Get Lottoid7 intLottoid = Jsonpath.getint ("Lottoid");8 9 //Get winning-numbers listTenlist<string> winningnumbers = Jsonpath.get ("Winning-numbers"); One A //The following statement returns a list,list that contains the 23,54 -list<integer> winningnumbers = Jsonpath.get ("Lotto.winners.winnerId");
If you are just interested in extracting a single value, you can do the following:
1 // "From" is a static import from Jsonpath. 2 int lottoid = from (Lottojson). GetInt ("lotto.lottoid");
You can also do some complicated operations, such as asking for winners.numbers and:
1 int sumofwinningnumbers = from (Lottojson). 2 GetInt ("Lotto.winning-numbers.sum ()");
Or find all the number that is greater than 10 and winnerid=23:
1 // The returned result is a list containing 45,34 and 23 2 list<integer> numbers = from (Lottojson). GetList (3 "Lotto.winners.find { It.winnerid = = 23}.numbers.findall {it > ten} ",4 Integer. Class);
Summary of Jsonpath usage methods of rest-assured