我需要将对象数组作为请求正文发送到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);