0

Following is Response body:

{
    "Updated_Fields": [
        "a",
        "b",
        "c",
        "d"
    ],
    "Invalid_Fields": [
        "cd",
        "ab"
    ]
}

I want to check that whether response body has

  1. two fields in invalid_field block
  2. 'cd' and 'ab' should be there in invalid_field block
JSONArray JSONResponseBody = new JSONArray(response.body().asString());

Assert.assertEquals(JSONResponseBody.getJSONObject(0).getString("Invalid_Fields"), "cd");

response.jsonPath().param("Invalid_Fields", "cd");

assertThat( response.asString(), hasJsonPath("Invalid_Fields.ab"));

Getting an error

Parth Makwana
  • 51
  • 1
  • 9

1 Answers1

0

One way you can use a library like gson to convert String to Java object and then apply standard Java logic ( sample below )

Gson Maven Dependency

private static final List INVALID_DATA = Arrays.asList("cd", "ab");

public static void main(String[] args)
{
    String input = "{ \"Updated_Fields\": [ \"a\", \"b\", \"c\", \"d\" ], \"Invalid_Fields\": [ \"cd\", \"ab\" ] }";
    Gson gson = new Gson();
    FieldData data = gson.fromJson(input, FieldData.class);
    System.out.println(isInvalidFields(data.Invalid_Fields));
}

private static boolean isInvalidFields(List<String> Invalid_Fields) {
    if(CollectionUtils.isEmpty(Invalid_Fields) || Invalid_Fields.size() != 2) {
     return false;   
    }
    return Invalid_Fields.containsAll(INVALID_DATA);
}

Definiton of class mapping to this data:

public class FieldData
{

    public List<String> Updated_Fields;

    public List<String> Invalid_Fields;

}
TechFree
  • 2,600
  • 1
  • 17
  • 18