【问题标题】:How to send JsonObject in body for post request using rest assured?如何使用放心在正文中发送 JsonObject 以进行发布请求?
【发布时间】:2017-03-09 09:10:39
【问题描述】:

我有一个使用 Google Gson 创建的 JsonObject。

JsonObject jsonObj = gson.fromJson(response1_json, JsonElement.class).getAsJsonObject();

我还对现有的 jsonobj 进行了一些修改,如下所示:

JsonObject newObject = new JsonObject();
            newObject.addProperty("age", "50");
            newObject.addProperty("name", "X");
jsonObj.get("data").getAsJsonArray().add(newObject);

现在,放心,我需要用这个 jsonobject 发送 post 请求。我尝试了以下方法,但它不起作用并引发异常:

Response postResponse = 
                    given()
            .cookie(apiTestSessionID)
            .header("Content-Type", "application/json")
            .body(jsonObj.getAsString())
            .when()
            .post("/post/Config");

请指导我。

【问题讨论】:

  • 你能发布你得到的异常吗?
  • 尝试添加 .contentType("application/json") 而不是设置为 header

标签: json gson rest-assured


【解决方案1】:

尝试下面的代码使用 Rest-assured 将 Json 发送到 Post 请求

//Get jsonObject from response
JsonObject jsonObj = gson.fromJson(response1_json, JsonElement.class).getAsJsonObject();


//Create new jsonObject and add some properties
JsonObject newObject = new JsonObject();
    newObject.addProperty("age", "50");
    newObject.addProperty("name", "X");

//Get jsonarray from jsonObject
JsonArray jArr = jsonObj.get("data").getAsJsonArray();

//Add new Object to array
jArr.add(newObject);

//Update new array back to jsonObject
jsonObj.add("data", jArr);

Response postResponse = 
                given()
        .cookie(apiTestSessionID)
        .contentType("application/json")
        .body(jsonObj.toString())
        .when()
        .post("/post/Config");

【讨论】:

  • 它对我有用,谢谢。我使用了 contentType(applicaiton/json),它解决了我的问题。
猜你喜欢
  • 2021-11-03
  • 2017-10-27
  • 1970-01-01
  • 2017-03-27
  • 2018-09-15
  • 2023-04-05
  • 1970-01-01
  • 2012-02-15
  • 2017-07-08
相关资源
最近更新 更多