如何使用简单的json在请求体下传递json数组

问题描述 投票:1回答:2

我使用下面的代码来自动化REST API。请帮助我理解如何将整个json数据放在下面提到的样本数据中,因为输入有数组,而到现在为止我使用了没有数组的平面jsons

Method Dummy()
{
    RestAssured.baseURI ="http://mydummyURL";
    RequestSpecification request = RestAssured.given();
    JSONObject requestParams = new JSONObject();
    requestParams.put("id", "THAILAND"); //Issue is with this code 
    request.header("Content-Type", "application/json");
    request.body(requestParams.toJSONString());
    Response response = request.post("/EndPoint");
}

json的身体看起来像这样

{
    "tag1": "value1",
    "tag2": "value2",
    "tag3": {
        "tag31": "value31",
        "tag32": "value32"
    },
    "tag4": [{
            "domainName": "ABC",
            "domainId": "123ABC123",
            "domainGUID": "TestMyDomain"
        },
        {
            "domainName": "XYZ",
            "domainId": "123XYZ123",
            "domainGUID": "TestMyDomain"
        }
    ]
}
java json rest-assured
2个回答
0
投票
ArrayList<JSONObject> array= new ArrayList<JSONObject>();
    JSONObject json= new JSONObject();

    try {
        json.put("key", "value");// your json
    } catch (JSONException e) {
        e.printStackTrace();
    }
    array.add(json);
    String printjsonarray= array.toString();// pass this into the request 

0
投票

如果你想在Java中使用JSON,请尝试JSONArray:

//Create your json payload object
JSONObject jsonObject = new JSONObject();
jsonObject.put("tag1", "value1");

//Create your domain objects 
JSONObject domainObj = new JSONObject();
domainObj.put("domainName", "ABC");
domainObj.put("domainId", "123ABC123");
domainObj.put("domainGUID", "TestMyDomain");

//Add created domain objects to json array
JSONArray domains = new JSONArray();
domains.put(domainObj);

//Add array to json payload object
jsonObject.put("tag4", domains);

RestAssured.given()
    .contentType(ContentType.JSON)
    .body(jsonObject.toString())
    .when()
    .post("http://www.example.com");

这是Javadoc看看https://stleary.github.io/JSON-java/

© www.soinside.com 2019 - 2024. All rights reserved.