I need to send an array of object as request body to POST API which looks like below.
[{
"k1": "v1",
"k2": "v2",
"k3": 1
}]
my dto file looks like below
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);
}
}
my client implementation looks like below
final HttpEntity<Request> httpEntity = new HttpEntity<Request>(requestBody, headers);
final ResponseEntity<String> responseEntity = restTemplate.exchange(URI, HttpMethod.POST, httpEntity, String.class);
Now i need help to build requestBody
being a JS dev , i am fairly new to Java. so, please be kind. ThankYou.
mentioned JSON
[{
"k1": "v1",
"k2": "v2",
"k3": 1
}]
is a list of Request
Object. So this requestBody
object must be like -
List<Request> requestBody = //your logic to build this variable;
Change in httpEntity
to accept this request body:
final HttpEntity<List<Request>> httpEntity = new HttpEntity<List<Request>>(requestBody, headers);
UPDATED: Example to build requestBody variable:
Request request1 = new Request("v1", "v2", 1);
List<Request> requestBody = new ArrayList<>();
requestBody.add(request1);