How to Send List of Long to Rest Controller Spring Boot

how to send a list of long to work with a rest controller

You actually send a json object here not a List

Send this in your post request instead.

 [1,2,3]

Your previous request could work if you had something like this

public class X {
@JsonFormat (with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
private List<Long> project_id;
}

@PostMapping("person/{id}/projects/")
public Person addProject(@PathVariable Long id, @RequestBody X x){..}

How to pass the list of integers as json data to spring boot rest API?

@RequestBody annotation read the whole request body, in your code you used it twice to read tow different parts of your request body. You can not achieve it like that. It is better to define new DTO class that contains all the things that you need to receive in request body, then you can read everything you want from that DTO, it can be done like below:

@Getter
@Setter
public class CreateAccountModel {

private Integer[] customerIds;
private Account account;
}

And this will be your endpoint:

@PostMapping("/createaccount")
public String createAccount(@RequestBody CreateAccountModel createAccountModel) {
return accountservices.createAccountService(
createAccountModel.getCustomerIds(),
createAccountModel.getAccount());
}

Then you can sen request like below:

curl -i -H "Content-Type:application/json" -d '{"customerIds": [1,2,3], "account": {}}' http://localhost:8080/createaccount


Related Topics



Leave a reply



Submit