使用来自 dto 的对象数组构建 HttpMethod POST 请求

Build a HttpMethod POST request with array of object from dto

我需要将对象数组作为请求正文发送到 POST API,如下所示。

[{
 "k1": "v1",
 "k2": "v2",
 "k3": 1
  }]

我的 dto 文件如下所示

public class Request {

    @JsonProperty("k1")
    private String k1;

    @JsonProperty("k2")
    private String k2;

    @JsonProperty("k3")
    private int k3;

    //setters and getters

    //override toString
    public String toString() {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        return gson.toJson(this);
    }

}

我的客户端实现如下所示

final HttpEntity<Request> httpEntity = new HttpEntity<Request>(requestBody, headers);

final ResponseEntity<String> responseEntity = restTemplate.exchange(URI, HttpMethod.POST, httpEntity, String.class);

现在我需要帮助来构建 requestBody

作为一名 JS 开发人员,我对 Java 还很陌生。所以,请善待。谢谢。

提到JSON

[{
 "k1": "v1",
 "k2": "v2",
 "k3": 1
  }]

Request 对象的列表。所以这个 requestBody 对象必须像 -

List<Request> requestBody = //your logic to build this variable;

更改 httpEntity 以接受此请求正文:

final HttpEntity<List<Request>> httpEntity = new HttpEntity<List<Request>>(requestBody, headers);

更新:构建 requestBody 变量的示例:

Request request1 = new Request("v1", "v2", 1);

List<Request> requestBody = new ArrayList<>();
requestBody.add(request1);