title: Spring Boot学习
date: 2020-01-14
原本在个人博客上写了一些博文,现转移到CSDN上
Spring Boot前后端传输json串数据
在前后端数据传输中,有的时候需要传输对象,一般将对象存储到json串中,串里包括对象的各种属性,由于传输的数据不是string,所以需要一些操作。
- 前端ajax方面
type:"POST",
contentType: "application/json",
data:JSON.stringify(match),//js对象转换为字符串
首先将javascript对象进行转换为字符串结构
- 后端数据接收方面
@RequestMapping(value = "/accept",method = RequestMethod.POST)
public JsonResult replace(@RequestBody ThemeVersionDTO themeVersionDTO){
...
}
首先,由于是接收数据,type设置为POST
其次,使用@RequestBody注解,@RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的)。
对@RequestBody注解的讲解,有一篇博客可以参考,讲的不错
链接
- 后端需要先设置dto,用来规划接收的数据的类型与个数,与前端的json串相对应
前端json串:
match.time = this.theme_tableData1[i].time;
match.themename = this.theme_tableData1[i].theme;
match.type= this.theme_tableData1[i].type;
console.log(match);
后台DTO文件:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ThemeVersionDTO {
String time;
String type;
String themename;
}
最终数据接收结果:
通过以上操作即可将数据成功传输。