Search code examples
jsonrestrest-assuredweb-api-testingrest-assured-jsonpath

Unable to get json node values


This is the json response format that I have and need to read the first node value "html". I have tried to few ways to get the value but unable to get it

[
   {
      "html": "<!DOCTYPE html>\n                                                <html>\n                                                    <head>\n                                                        <\/html>\n                                                \n",
<\/html>\n                                                \n",
      "headers": {},
      "subject": "Register new account",
      "messageId": "[email protected]",
      "priority": "normal",
      "from": [],
      "to": [],
      "date": "2019-08-12T11:03:20.000Z",
      "receivedDate": "2019-08-12T11:09:42.000Z",
      "receivedAt": "2019-08-12T11:09:44.900Z"
   },
   {+},
   {+}
]

I tried couple of things

    RequestSpecification emailReq = given().with().pathParam("email",emailName);
        Response emailResp = emailReq.contentType("application/json").get("https://restmail.net/mail/{email}");

JSONObject value = new JSONObject(emailResp.asString());

I got this error

org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:505)

and then I removed this last line to use But this does not gives me error. pls refer screenshot for this

JSONArray responseJson = new JSONArray(emailResp.asString());

Tried this as well

List<HashMap<String, Object>> jsonObjectsInArray = emailResp.jsonPath().getList("$");
for (HashMap<String, Object> singleLeg : jsonObjectsInArray) {
    String value = (String) singleLeg.get("html");

}

But again array size is 0

Need some suggestion of how to get the value of node - "html". Pls suggest. what mistake am I doing here?

Thanks in advance

for the second way


Solution

  • RequestSpecification emailReq = given().with().pathParam("email",emailName); 
    int retries = 5; 
    List<HashMap<String, Object>> emails = Arrays.asList(); 
    . . . 
    emailResp = emailReq.get("restmail.net/mail{email}"); 
    if (emailResp.getStatusCode() == 200) { emails = emailResp.jsonPath().getList("$");
    String email = emails.get(0).get("html").toString();