springboot 接收JSON
Controller接收JSON
在springmvc里使用 @ResponseBody 可以返回JSON. 同样的使用 @RequestBody 可以接收JSON.
在Controller方法带有
@RequestBody注解的参数,意味着请求的HTTP消息体的内容是一个JSON.
springboot默认使用Jackson来处理序列化和反序列化.
建一个带springmvc的 springboot项目
User model:set, get, toString方法
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
}Controller:
@Controller
public class IndexController {
@RequestMapping(path="/testjson.json")
@ResponseBody
public String index(@RequestBody User user){
System.out.println(user);
return "用户名 "+user.getName()+" 年龄 "+user.getAge();
}
}测试效果
使用curl工具:
curl -XPOST 'http://127.0.0.1:8080/testjson.json' -H 'content-Type:application/json' -d'
{
"name":"scott",
"age":"20"
}
'上述curl命令,将会发起一个POST请求,用 -H 参数设置HTTP头用 -d 参数设置请求体内容。curl命令在Linux和Mac系统是内置的,在Windows系统下则需要自己安装。
控制台打印:
User [name=scott, age=20]
命令行返回:

相关推荐
Lzs 2020-10-23
聚合室 2020-11-16
零 2020-09-18
Justhavefun 2020-10-22
ChaITSimpleLove 2020-10-06
周游列国之仕子 2020-09-15
afanti 2020-09-16
88234852 2020-09-15
YClimb 2020-09-15
风雨断肠人 2020-09-04
卖口粥湛蓝的天空 2020-09-15
stulen 2020-09-15
pythonxuexi 2020-09-06
abfdada 2020-08-26
梦的天空 2020-08-25