SpringBoot项目中对于数组类型数据接收方式

SpringBoot项目中对于数组类型数据接收方式

一、先定义一个简单的实体类

package cn.js.domain;

import lombok.Data;

@Data
public class Person {
    private String name;
    private int age;
}

二、前端传递的json数据方式:

1.前端传递普通json,后端用对象接收:

{
    "name":"张三",
     "age":12
}
用对象接收json:
@PostMapping("/test1")
  public String test(@RequestBody Person person){
      System.out.println("name"+person.getName());
      System.out.println("age"+ person.getAge());

      return "成功";
  }

2.前端传递json数组:

{
    "name":["小明","小三","小四"],
     "age":12
}
用Map接收json数组:
 @PostMapping("/test2")
 public String test2(@RequestBody Map hasaMap){
        ArrayList arrayList = new ArrayList();
        arrayList = (ArrayList) hasaMap.get("name");
        String str = (String) arrayList.get(0);
        System.out.println("arrayList"+str);
        System.out.println("name"+hasaMap.get("name"));
        System.out.println("age"+ hasaMap.get("age")); 
   return "成功";
}

3.前端传递json数组,后端用集合接收Josn数组

{
    "name":["小明","小三","小四"]
}
用Map嵌套List接收 json数组
    @PostMapping("/test2")
    public String test3(@RequestBody  Map hasaMap){
        System.out.println("name"+hasaMap.get("name"));
    return "成功";
}

你可能感兴趣的:(SpringBoot,spring,boot)