Spring MVC 如何在spring Boot api中通过请求体获取对象列表

62lalag4  于 2022-11-15  发布在  Spring
关注(0)|答案(2)|浏览(178)

通过控制器中的@RequestBody获取对象列表,并处理list中的每个对象以执行业务逻辑。
我已经试过了,但没有效果

@RequestMapping(value="/updateservicetype", method=RequestMethod.POST,produces="application/json")
    public @ResponseBody ServiceTypesMessage updateServiceType(@RequestBody List<BarberServiceType> serviceTypes,final HttpServletResponse response){

还尝试了以下操作:

@RequestMapping(value="/updateservicetype", method=RequestMethod.POST,produces="application/json")
    public @ResponseBody ServiceTypesMessage updateServiceType(@RequestBody BarberServiceType[] serviceTypes,final HttpServletResponse response){
bihw5rsg

bihw5rsg1#

以下内容适合我

@RequestMapping(value = "/payments", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody List<Payment> batchCreate(@RequestBody List<Payment> payments) {
  return paymentService.create(payments);
}

类路径中需要Jackson

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.0</version>
</dependency>

詹森在放是

[{"sort":"10-20-30","account":"1234"},{"sort":"10-20-30","account":"1234"}]
w41d8nur

w41d8nur2#

你应该为你所需要的列表使用一个 Package 类,换句话说,创建一个新的类并将其命名为“BarverServiceTypeRequest”这个类应该包含你的列表:

public class BarberServiceTypeRequest{
    private List<BarberServiceType> serviceTypes;
    public List<BarberServiceType> getserviceTypes() {
        return serviceTypes;
    }

    public void setServiceTypes(List<BarberServiceType>serviceTypes) {
        this.date = date;
    }

那么你的控制器就会像这样:

@RequestMapping(value="/updateservicetype", method=RequestMethod.POST,produces="application/json")
    public @ResponseBody ServiceTypesMessage updateServiceType(@RequestBody BarberServiceTypeRequest request, final HttpServletResponse response){

您的JSON对象如下所示:

{
   "serviceTypes": [{"sort":"10-20-30","account":"1234"},{"sort":"10-20-30","account":"1234"}]
}

请确保您可以通过以下方式访问列表:

request.getserviceTypes();

相关问题