无法获取json节点值

时间:2019-08-12 13:05:41

标签: json rest rest-assured web-api-testing rest-assured-jsonpath

这是我必须读取的第一个节点值“ html”的json响应格式。我尝试了几种获取价值但无法获取价值的方法

[
   {
      "html": "<!DOCTYPE html>\n                                                <html>\n                                                    <head>\n                                                        <\/html>\n                                                \n",
<\/html>\n                                                \n",
      "headers": {},
      "subject": "Register new account",
      "messageId": "475603953.247.1565607800153@dfrsbdd201.abc.com.au",
      "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"
   },
   {+},
   {+}
]

我尝试了几件事

    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());

我收到此错误

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

,然后我删除了要使用的最后一行,但这没有给我错误。请参阅此屏幕截图

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

也尝试过

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

}

但数组大小再次为0

需要一些有关如何获取节点值“ html”的建议。请建议。我在这里犯什么错误?

预先感谢

for the second way

1 个答案:

答案 0 :(得分:0)

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();