JayC
JayC

Reputation: 2292

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]

Upvotes: 2

Views: 1383

Answers (3)

Norayr Sargsyan
Norayr Sargsyan

Reputation: 1868

With the Rest assured if you want to get the last item from array, you can use:

.extract()
.path("items[-1].value");

Upvotes: 0

Arsal
Arsal

Reputation: 1006

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

Upvotes: 1

SmulianJulian
SmulianJulian

Reputation: 802

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.

Upvotes: 1

Related Questions