0

Im using JsonPath to Assert on some of the values returned from an api response but having a small issue with asserting the response.

Heres the response i get:

[{"Id":75969,StartDate":"2016-07-01","EndDate":"2021-04-30","duration":5640}]

Lets say i want to Assert on the Start date. The method I created looks like this:

   public void checkStartDate(String expectedStartDate) {

    String responseBody = response.getBody().asString();

    JsonPath values = new JsonPath(responseBody);

    Assert.assertEquals(expectedStartDate,values.getString("startDate"));
}

The expectedStartDate that i pass in to the method is 2016-07-01 and the date i get back from the JsonPath object is [2016-07-01] which causes the assertion to fail.

Does anyone know what i can do to with JsonPath in order to remove the square braces from the value that im extracting from the response string?

bobe_b
  • 187
  • 1
  • 2
  • 21

3 Answers3

0

This might help you. Try the below code :

  public void checkStartDate(String expectedStartDate) {
    String responseBody = response.getBody().asString();
    String startDate = JsonPath.read(responseBody, "$.[0].StartDate");
    Assert.assertEquals(expectedStartDate, startDate);
  }
Sujit kumar
  • 131
  • 10
0

When you read with "getList", you will get the exact value.

    JsonPath values = new JsonPath(responseBody);
    List<String> valuesToRead = values.getList("StartDate");
    for (String value : valuesToRead) {
        System.out.println(value);
    }
0

I think the problem is the reponse is an array of objects, rather than just a single object? So you want to check against jp.getString("[0].StartDate")

Working example:

JsonPath jp = JsonPath.from("[{\"Id\":75969,\"StartDate\":\"2016-07-01\",\"EndDate\":\"2021-04-30\",\"duration\":5640}]");
System.out.println("2016-07-01".equals(jp.getString("[0].StartDate")));

Prints: true

aarbor
  • 1,398
  • 1
  • 9
  • 24