标签:mode group core framework 2.7 浏览器插件 img public import
关于什么是json以及基本使用技巧,为什么使用json等等,这里不再重复,直接进入主题
注:服务端接收json数据还原为java对象,称为反序列化,反之,将java对象作为响应转换为json数据发回给客户端,称为序列化
如果使用的是spring boot框架,导入spring boot相关依赖后,就存在相关依赖,无需重复,否则会报错;
如果使用的是spring MVC框架,就需要手动导入相关依赖(比如Jackson),直接上代码,添加到pom文件中
<!-- jackson依赖 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.7.0</version> </dependency>
此处需注意,别把@RequestBody和@ResponseBody放错地方,观察源代码可知,@RequestBody只能添加在参数前,而@ResponseBody添加在类和方法前
import com.jeat.clinic.controller.OVmodel.BookType; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.Map; /** * @author * @class JsonTest * @Abstract * @date 2019/02/19 */ @RestController public class JsonTest { /** * 以实体类接收 * @param bookType * @param request * @return * {"id":12,"typeName":"类型1"} */ @RequestMapping(value="acceptJsonByEntity",method = RequestMethod.POST) public BookType acceptJsonByEntity(@RequestBody BookType bookType, HttpServletRequest request){ System.out.println("当前http请求方式为:"+request.getMethod()); System.out.println(bookType); return bookType; } /** * 以map方式接收 * @param paramsMap * @param request * @return */ @RequestMapping(value="acceptJsonByMap") public Map<String,Object> acceptJsonByMap(@RequestBody Map<String,Object> paramsMap, HttpServletRequest request){ System.out.println("当前http请求方式为:"+request.getMethod()); System.out.println(paramsMap); return paramsMap; } /** * 以list方式接收(以json数组形式传递) * @param bookTypeList * @param request * @return */ @RequestMapping(value="acceptJsonByList") public List<BookType> acceptJsonByList(@RequestBody List<BookType> bookTypeList, HttpServletRequest request){ System.out.println("当前http请求方式为:"+request.getMethod()); System.out.println(bookTypeList); return bookTypeList; } /** * 以单独属性形式接收 * @param id * @param name * @return */ @RequestMapping("acceptJsonBySingleParam") public MultiValueMap acceptJsonByRequestParam(@RequestBody MultiValueMap params /* @RequestBody int userId, @RequestBody String userName*/ ) { System.out.println(params.get("userId")+","+params.get("userName")); return params; } }
响应结果:
客户端结果:
响应结果:
客户端结果:
响应结果:
客户端结果:
标签:mode group core framework 2.7 浏览器插件 img public import
原文地址:https://www.cnblogs.com/jeat/p/10400218.html