簡體   English   中英

如何獲取 JSON 屬性並將其存儲在 JAVA 的數組中?

[英]How do I get a JSON attribute and store it in an array in JAVA?

我試圖在我的 RestAssured TestNG 測試中斷言,對於我的 JSON 文件中的每個給定 ReportCodeNbr,都有一個正確的 UID 值。

我可以通過使用硬編碼索引值引用每個 json 部分來成功地做到這一點,就像在這個例子中一樣,但是,部分的順序可以改變,這會改變索引值並破壞測試。

如何最好地存儲每個部分的 ReportCodeNbr 的所有值,然后斷言 UID 是正確的,而不使用像我的示例中那樣的硬編碼索引值?

一位同事建議了一個數組,但我不確定如何 go 關於這個。

包含兩個數據對象的部分 JSON 文件:

[
    {
        "Url": null,
        "DataSteward": null,
        "ReportAuthor": null,
        "ReportKey": "100PercentSponsorFundedFaculty",
        "SystemType": null,
        "ReportTitle": "Report",
        "ReportCodeNbr": "FIN1065",
        "PropertyList": null,
        "Title": "100 Percent Sponsor-Funded Faculty",
        "Uid": "97d17dbd-9c3b-46aa-ae0e-39603a32250f"
    },
    {
        "Url": null,
        "DataSteward": null,
        "ReportAuthor": null,
        "ReportKey": "2013BaseYearPaidFTEReport",
        "SystemType": null,
        "ReportTitle": "Report",
        "ReportCodeNbr": "FIN1075",
        "PropertyList": null,
        "Title": "100 Percent Sponsor-Funded Faculty",
        "Uid": "97b3f1e0-b17d-448b-86ae-6ed6b432dcd2"
    }
]

使用硬編碼索引值成功測試:

@Test
    public static void firstTest() {
       Response response = given().when().get(baseURI);
       response.then()
               .assertThat().body("ReportCodeNbr[1]", equalTo("FIN1075"))
               .assertThat().body("Uid[1]", equalTo("97b3f1e0-b17d-448b-86ae-6ed6b432dcd2"));}

像這樣的東西應該工作:

Response response = given().when().get(baseURI);    
List<String> jsonResponse = response.jsonPath().getList("Uid");

然后您可以 Stream 列表並斷言它包含您正在尋找的值,如果您使用 >= java 1.8。 否則,只需使用 for 循環。

有很多方法可以做到這一點。 有關更多信息,請參閱此處: Testing ExcellenceRest Assured Docs (jsonPath)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM