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

How to pull the last jsonPath value in Java?

您好,我想问一下如何检索 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

现在它正在打印所有交易 ID。它应该只拉最新的,意思是底部的,其中 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"

        },
    ]
}

既然已经存储了一个新的数据集,我将如何编写一个 java 代码来提取 transactionId "NewID"?

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

的内容

使用 Gson api

它转换 json -->>java 对象

http://tutorials.jenkov.com/java-json/gson.html#parsing-json-into-java-objects

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

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

我不确定如何在您的 JSON 数组中正确实现它,但我希望这能让您朝着正确的方向前进。

好吧,你可以使用 getList 而不是 getString 例如

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

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

如果你想从数组中获取最后一项,请放心,你可以使用:

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