Search code examples
javajsoneclipserest-assuredrest-assured-jsonpath

How to print a value by comparing 2 fields inside JSON - RestAssured


Consider the following dataset:

[
    {
        "_id": 1234,
        "bagnumber": "A",
        "bagtype": "coin"
    },
    {
        "_id": 2345,
        "bagnumber": "B",
        "bagtype": "cash"
    },
    {
        "_id": 3456,
        "bagnumber": "C",
        "bagtype": "coin"
    },
    {
        "_id": 5678,
        "bagnumber": "D",
        "bagtype": "cash"
    }
]

I need to extract and print the bag numbers that have the bag type "cash" exclusively. Thus, the desired output should be:

Bag numbers are: B, D

I attempted to extract the bag numbers first using a list:

List<String> bagNumbers = response.jsonPath().getList("bagnumber");

Subsequently, I tried to retrieve the bag types using the same list and attempted to compare the two lists. However, my attempts were unsuccessful, possibly indicating an overly complicated approach.

Could someone kindly suggest a more efficient solution? Perhaps utilizing the Matchers class or any other suitable approach would be appreciated.


Solution

  • GSON

    I suggest Gson or Jackson for Json process.

    If the input are string, convert it to JsonArray using:

    JsonArray jsonData = new Gson().fromJson(jsonString, JsonArray.class);
    

    Create a List containing result:

    List<String> listBadCashNumber =new ArrayList<>();
    

    Start iterating through array:

    for(int i = 0;i<jsonData.size();i++){
        JsonObject bag = jsonData.get(i).getAsJsonObject();// Because each element off array is a object
        if(bag.get("bagtype").getAsString().equals("cash")){ // Compare the field 'bagtype', you should handle the null if needed
            listBadCashNumber.add(bag.get("bagnumber").getAsString()); // Add to result list
        }
    }
    System.out.println("Bag numbers are: "+listBadCashNumber);
    

    And the result is:

    Bag numbers are: [B, D]