如何发送长列表以与休息控制器一起工作

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

我正在研究 api。我想发送 Long 的列表以通过 ID 查找项目。 这是休息控制器:


@PostMapping("person/{id}/projects/")
    @JsonFormat (with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
    public Person addProject(@PathVariable Long id, @RequestBody List<Long> project_id){
        Optional<Person> person = personRepo.findById(id);
        Person person1 = person.get();
        for(int i=0; i<project_id.size(); i++){
            System.out.println(project_id.get(i));
            Optional <Project> project = projectRepo.findById(project_id.get(i));
            person1.getProjectList().add(project.get());

        }
        System.out.println((person1.getProjectList()).toString());

        return personRepo.save(person1);
    }

这是我发送给 rest-controller 的请求

{
    "project_id": [1,2,3]
}

我收到这个异常:

JSON parse error: Cannot deserialize instance of `java.util.ArrayList<java.lang.Long>` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList<java.lang.Long>` out of START_OBJECT token\n at [Source: (PushbackInputStream); line: 1, column: 1]

我已经尝试了与 PathVariable 相同的代码作为 id,有效。但是这个剂量

你实际上在这里发送了一个 json 对象而不是一个列表

改为在您的 post 请求中发送。

 [1,2,3]

如果你有这样的东西,你之前的请求就可以工作

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){..}