⛪ 专栏地址 系列教程更新中 🚀 专栏介绍: 本专栏为SpringBoot+Spring+Mybatis的系列零基础教程,从框架的基础知识讲起,从0开始实现一个在线教育实战项目
例如,假设有以下请求正文:
{
"name": "Tom",
"age": 20
}
那么可以定义一个如下的方法:
@PostMapping("/users")
public void addUser(@RequestBody User user) {
// 处理
}
需要注意的是,为了能够正确地将请求正文中的数据转换为对象,需要在 Spring Boot 应用程序中配置一个 JSON 解析器,通常情况下可以使用 Jackson 或者 Gson 等库来实现。在 Spring Boot 应用程序中,只需要在 pom.xml 文件中添加相应的依赖即可自动配置。
public class Chapter {
private int id;
private int videoId;
private String title;
@Override
public String toString() {
return "Chapter{" +
"id=" + id +
", videoId=" + videoId +
", title='" + title + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getVideoId() {
return videoId;
}
public void setVideoId(int videoId) {
this.videoId = videoId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
public class Video implements Serializable {
//Video的属性
private int id;
private String title;
private String summary;
private int price;
private String coverImg;
private Date createTime;
private List<Chapter> chapterList;}
//视频控制器
@RestController //表示是一个控制器,使用这个会返回json数据,使用@Controller就不会帮我们返回控制器
@RequestMapping("/api/v1/pub/video") //pub表示任何人可访问
public class VideaController {
//注入
@Autowired
private VideoService videoService;
//@RequestMapping(method = RequestMethod.GET)
@GetMapping("list")
public JsonData list(){
List<Video> list=videoService.listVideo();
return JsonData.buildSuccess(list);
}
@PostMapping("sava_video_chapter")
public JsonData savaVideoChapter(@RequestBody Video video){
System.out.println(video.toString());
return JsonData.buildSuccess("");
}
}
传入的数据:
{
"id":1,
"title":"测试",
"chapterList":[
{ "id":"1",
"videoId":"1",
"title":"测试1"
}
]
}