如何发送JsonObject的正文发送请求使用放心? [英] How to send JsonObject in body for post request using rest assured?

查看:109
本文介绍了如何发送JsonObject的正文发送请求使用放心?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Google Gson创建了JsonObject。

I have a JsonObject created using Google Gson.

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

我还对现有的jsonobj进行了如下修改:

Also i made some modification to existing jsonobj as below :

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

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

Now, using rest assured, i need to send the post request with this jsonobject. I tried the following but it doesn't work and throws exception:

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

请指导我。

Please guide me on this.

推荐答案

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

Try below code to send Json to a Post request using Rest-assured

//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");

这篇关于如何发送JsonObject的正文发送请求使用放心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆