一、先定义一个简单的实体类
package com.gec.domain;
import lombok.Data;
@Data
public class Person {
private String name;
private int age;
}
二、编写前端传递的json数据
1.前端传递普通json,后端用对象接收
{
"name":"小明",
"age":12
}
//用对象接收json
@PostMapping("/jsonServlet1")
public String jsonServlet1(@RequestBody Person person){
System.out.println("name"+person.getName());
System.out.println("age"+ person.getAge());
// System.out.println("name"+name);
// System.out.println("age"+age);
return "成功";
}
2.前端传递json数组,文章来源:https://www.toymoban.com/news/detail-522181.html
{
"name":["小明","小王","小刘"],
"age":12
}
//用Map接收json数组
@PostMapping("/jsonServlet4")
public String jsonServlet4(@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数组文章来源地址https://www.toymoban.com/news/detail-522181.html
{
"name":["小明","小王","小刘"]
}
//用Map嵌套list接收json数组
@PostMapping("/jsonServlet5")
public String jsonServlet5(@RequestBody Map<String,List > hasaMap){
System.out.println("name"+hasaMap.get("name"));
System.out.println("age"+hasaMap.get("age"));
return "成功";
}
到了这里,关于前端传递Json格式,后端如何用多种方式接收的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!