Search code examples
javajsonpathrest-assured-jsonpath

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

  • 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))