响应Json数据
后端接收Json数据,使用
@RequestBody
注解,获得Json数据@Controller public class HelloController { @RequestMapping(path = "/hello") public String hello(@RequestBody String body) { System.out.println(body); //输出接收到的Json数据 return "success"; } }
将获得的Json数据,转换成Java对象
导入jar包
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.0</version> </dependency>
将接受的类型改为要接收的Java对象
package com.oylong.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloController { @RequestMapping(path = "/hello") public String hello(User user) { System.out.println(user); //输出Json的内容 return "success"; } }
这里的前提是,接收的Json数据的key必须要于Java对象成员名称相对应
返回Json数据
直接返回对象即可,只需要加一个
@ResponseBody
注解SpringMVC会自动将对象转换成Json数据@Controller public class HelloController { @RequestMapping(path = "/hello") public @ResponseBody User hello(User user) { System.out.println(user); //输出Json的内容 return user; } }