1 @RequestBody 处理类型
在项目中经常看到controller 中有 @RequestBody 字样,他到底有什么作用?
一般使用表单提交数据时不需要使用@RequestBody 即可自动封装数据到对应的 Bean 中。@RequestBody 用来处理Content-Type: application/json, application/xml等
它是通过使用HandlerAdapter 配置的HttpMessageConverters来解析post data body,然后绑定到相应的bean上的。
说明:使用 @RequestBody 解析数据需要添加 jackson 或 fastjson 依赖包。
maven 引入 fastjson 包
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.51</version> </dependency>
2 对象 和 json 相互转换
在项目中经常会遇到对象和 json 之间相互转换,公共类 和 json 对象转换, 静态内部类 和 json 对象转换
2.1 没有内部类时 Student 类
@Data public class Student { private String id; private String name; private int age; private String sex; @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
json 和 对象 相互转换
public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); Student student = new Student(); student.setName("good"); String s = mapper.writeValueAsString(student); System.out.println(s); Student hd2 = mapper.readValue(s, Student.class); System.out.println(hd2); }
2.2 有静态内部类时 Student 类
@Data public class Student { private String id; private String name; private int age; private String sex; private HomeData homeData; private BigDecimal salary; private String[] tel; @Override public String toString() { return ToStringBuilder.reflectionToString(this); } @Data public static class HomeData{ private Address address; @Override public String toString() { return ToStringBuilder.reflectionToString(this); } @Data public static class Address { private String country; private String city; @Override public String toString() { return ToStringBuilder.reflectionToString(this); } } } }
json 和 对象 之间相互转换
public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); Student student = new Student(); Student.HomeData homeData = new Student.HomeData(); Student.HomeData.Address address = new Student.HomeData.Address(); address.setCountry("中国"); address.setCity("上海"); homeData.setAddress(address); student.setHomeData(homeData); String s = mapper.writeValueAsString(address); System.out.println(s); Student.HomeData.Address hd2 = mapper.readValue(s, Student.HomeData.Address.class); System.out.println(hd2); }
说明:主要方法有 mapper.writeValueAsString 和 mapper.readValue