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

77 Views Asked by At

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.

2

There are 2 best solutions below

7
cuong02n On BEST ANSWER

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]
0
Raymond Choi On

You may try JSON library Josson and your request can be done by short statement and functions.

https://github.com/octomix/josson

Josson josson = Josson.fromJsonString(
    "[" +
    "    {" +
    "        \"_id\": 1234," +
    "        \"bagnumber\": \"A\"," +
    "        \"bagtype\": \"coin\"" +
    "    }," +
    "    {" +
    "        \"_id\": 2345," +
    "        \"bagnumber\": \"B\"," +
    "        \"bagtype\": \"cash\"" +
    "    }," +
    "    {" +
    "        \"_id\": 3456," +
    "        \"bagnumber\": \"C\"," +
    "        \"bagtype\": \"coin\"" +
    "    }," +
    "    {" +
    "        \"_id\": 5678," +
    "        \"bagnumber\": \"D\"," +
    "        \"bagtype\": \"cash\"" +
    "    }" +
    "]");
String output = josson.getString("[bagtype='cash']*.bagnumber.join(', ').prepend('Bag numbers are: ')");
System.out.println(output); // "Bag numbers are: B, D"