如何在Java中提取最后一个jsonPath值?

时间:2018-03-03 01:00:42

标签: java jsonpath rest-assured-jsonpath

您好我想问一下如何检索jsonPath中的最后一个值

{
    "testing": [
        {
            "transactionId": "5a99dcf84b7f633a5489805d",
            "trackingId": "555112",
            "tn": "6095555112",
            "customerName": "John",
            "customerLastName": "Chan"
        },
        {
            "transactionId": "5a99dd3f4b7f633a54898068",
            "tn": "6095555112",
            "trackingId": "555112",
            "customerName": "Amanda",
            "customerLastName": "Brown"

        }
    ]
}

我的Java代码示例行

System.out.println("response.prettyPrint() = " + response.jsonPath().getString("testing.transactionId"));

输出

response.prettyPrint() = 5a99dcf84b7f633a5489805d,5a99dcf84b7f633a5489805d

现在它正在打印所有transactionIds。它应该只是拉最新的一个意味着底部的一个,其中transactionId =“5a99dd3f4b7f633a54898068”

如果有新值进入(通过后端逻辑,则会在其中添加另一组值)。如何编写一条能够提取最新值集的行?

示例

{
    "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"

        },
    ]
}

现在已经存储了一个新的数据集,我将如何编写一个可以提取transactionId“NewID”的java代码?

我不想硬编码并写一些类似“.transactionId [0]”[1]或[2]

的内容

2 个答案:

答案 0 :(得分:1)

我希望这会有所帮助。我不知道确切的代码,但我知道在数组中你可以获得最后一项如...

 ARRAY.get(ARRAY.size()-1) 

我不确定如何在JSON数组中正确实现它,但我希望这会向您发送正确的方向。

答案 1 :(得分:1)

您可以使用getString而不是getList。 例如

List<String> strList = response.jsonPath().getList("testing.transactionId");

System.out.println("last value is " + strList.get(strList.size()-1))