首页 > 解决方案 > 放心 - 如何在“JSONObject body”中传递对象

问题描述

以下代码执行时

public void RegistrationSuccessful()
{       
    RestAssured.baseURI ="http://restapi.demoqa.com/customer";
    RequestSpecification request = RestAssured.given();

    JSONObject requestParams = new JSONObject();
    requestParams.put("FirstName", "Virender"); // Cast
    requestParams.put("LastName", "Singh");
    request.body(requestParams.toJSONString());
    Response response = request.post("/register");
}

返回

{
    "FirstName": "Virender",
    "LastName": "Singh"
}

有人可以指导以下 JSON 的放心代码吗?

{
    "FirstName": "Virender",
    "LastName": "Singh",
    "Address": {
        "Line1": "flat no 101",
        "area": "andheri",
        "City": "Mumbai"
    }
}

标签: rest-assured

解决方案


您可以为此使用 JSONObject、HashMap 或 POJO

使用JSONObject的示例代码,我没有测试过下面的代码,所以如果它不起作用,请告诉我

JSONObject requestparams = new JSONObject();
JSONArray authArray = new JSONArray();
JSONObject authparam = new JSONObject();

    requestParams.put("FirstName", "Virender");
    requestParams.put("LastName", "Singh");

        authparam.put("Line1", "Flat no 101");
        authparam.put("Area", "Andheri");
        authparam.put("City", "Mumbai");
        authArray.add(authparam);

        requestparams.put("Address", authparam);

    req.body(requestparams.toJSONString());
    Response response = req.post("http://restapi.demoqa.com/customer/register");

也是使用HashMap的示例

Map<String, Object> map = new HashMap<>();
map.put("FirstName", "Virender");
map.put("LastName", "Singh");
map.put("Address", Arrays.asList(new HashMap<String, Object>() {{
    put("Line1", "Flat no 101");
    put("Area", "Andheri");
    put("City", "Mumbai");
}}
));

RequestSpecification req=RestAssured.given();
req.header("Content-Type","application/json");
req.body(map).when();
Response resp = req.post("http://restapi.demoqa.com/customer/register");

推荐阅读