简体   繁体   中英

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

I am trying to assert in my RestAssured TestNG test that for every given ReportCodeNbr in my JSON file there is a correct UID value.

I was able to successfully do this by referencing each json section with a hard-coded index value like in this example, however, the order of the sections can change which changes the index value and breaks the test.

How can I best store all of the values for ReportCodeNbr for each section and then assert that the UID is correct without using a hard-coded index value like in my example?

A colleague suggested an array, but I am not sure how to go about this.

Partial JSON file with two objects of data:

[
    {
        "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"
    }
]

Successful test with hard-coded index values:

@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"));}

Something like this should work:

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

Then you can Stream the list and assert it contains the value you are looking for if you are using >= java 1.8. Otherwise just use a for-loop.

There are a host of ways to do this. Refer here for more information: Testing Excellence , Rest Assured Docs (jsonPath)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM