'How to pull the last jsonPath value in Java?
Hello I wanted to ask how to retrieve the last value in a jsonPath
{
"testing": [
{
"transactionId": "5a99dcf84b7f633a5489805d",
"trackingId": "555112",
"tn": "6095555112",
"customerName": "John",
"customerLastName": "Chan"
},
{
"transactionId": "5a99dd3f4b7f633a54898068",
"tn": "6095555112",
"trackingId": "555112",
"customerName": "Amanda",
"customerLastName": "Brown"
}
]
}
My Java code Sample line
System.out.println("response.prettyPrint() = " + response.jsonPath().getString("testing.transactionId"));
Output
response.prettyPrint() = 5a99dcf84b7f633a5489805d,5a99dcf84b7f633a5489805d
Right now it is printing all transactionIds. It should be only pulling the latest one meaning the bottom one where transactionId = "5a99dd3f4b7f633a54898068"
If a new value come in (through back end logic, will add another set of values into this). How can I write a line that will pull the latest values set?
Example
{
"testing": [
{
"transactionId": "5a99dcf84b7f633a5489805d",
"trackingId": "555112",
"tn": "6095555112",
"customerName": "John",
"customerLastName": "Chan"
},
{
"transactionId": "5a99dd3f4b7f633a54898068",
"tn": "6095555112",
"trackingId": "555112",
"customerName": "Amanda",
"customerLastName": "Brown"
},
{
"transactionId": "newID",
"tn": "6095555112",
"trackingId": "555112",
"customerName": "Amanda",
"customerLastName": "Brown"
},
]
}
Now that a new dataset has been stored, How will I write a java code that would pull the transactionId "NewID"?
I don't want to hardcode and write something like ".transactionId[0]" [1] or [2]
Solution 1:[1]
Well instead of using getString you can use getList
For e.g
List<String> strList = response.jsonPath().getList("testing.transactionId");
System.out.println("last value is " + strList.get(strList.size()-1))
Solution 2:[2]
I hope this helps. I don't know the exact code but I know in an array you can get the last item like...
ARRAY.get(ARRAY.size()-1)
I am not sure how to properly implement that in your JSON array but I hope this sends you in the right direction.
Solution 3:[3]
use Gson api
it converts json -->>java object
http://tutorials.jenkov.com/java-json/gson.html#parsing-json-into-java-objects
Solution 4:[4]
With the Rest assured if you want to get the last item from array, you can use:
.extract()
.path("items[-1].value");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arsal |
| Solution 2 | SmulianJulian |
| Solution 3 | goldbalaji13 |
| Solution 4 | Norayr Sargsyan |
