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]
命令行返回:
以上就是springboot接收JSON实现示例解析的详细内容,更多关于springboot接收JSON的资料请关注脚本之家其它相关文章!
相关文章
Java LocalDateTime获取时间信息、格式化、转换为数字时间戳代码示例
其实我们在Java项目中对日期进行格式化,主要是利用一些日期格式化类,下面这篇文章主要给大家介绍了关于Java LocalDateTime获取时间信息、格式化、转换为数字时间戳的相关资料,需要的朋友可以参考下2023-11-11亲测SpringBoot参数传递及@RequestBody注解---踩过的坑及解决
这篇文章主要介绍了亲测SpringBoot参数传递及@RequestBody注解---踩过的坑及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-10-10
最新评论