Spring Boot 处理 JSON 数据
JSON 是目前主流的前后端数据传输方式,当 Controller 中返回的是一个 Java 对象或 List 集合时,Spring Boot 将自动把它转换成 JSON 数据。
Spring Boot 中内置了 JSON 解析功能,当你在项目中,添加了 spring-boot-starter-web 模块之后,即可看到默认包含 Jackson 解析器,也可以换成 Fastjson 等其他解析器。
- 编辑 Book 类
- class Book {
private Integer id;private String name;private String author;@JsonIgnoreprivate Float price;@JsonFormat(pattern = \\\"yyyy-MM-dd\\\")private Date bookPublicationDate;// getter 和 setter 方法private Integer id; private String name; private String author; @JsonIgnore private Float price; @JsonFormat(pattern = \\\"yyyy-MM-dd\\\") private Date bookPublicationDate; // getter 和 setter 方法
}
- 编辑 BookController
返回数据的时候,需要使用 @ResponseBody 注解。如果经常使用 @Controller 和 @ResponseBody 注解,则可以使用 @RestController 组合注解来替代。
@RestController
public class BookController {
@GetMapping(\\\"/book\\\")public Book book(){Book book = new Book();book.setId(1);book.setName(\\\"《码农翻身:用故事给技术加点料》\\\");book.setAuthor(\\\"刘欣\\\");book.setPrice(69f);book.setBookPublicationDate(new Date());return book;}@GetMapping(\\\"/book\\\") public Book book(){ Book book = new Book(); book.setId(1); book.setName(\\\"《码农翻身:用故事给技术加点料》\\\"); book.setAuthor(\\\"刘欣\\\"); book.setPrice(69f); book.setBookPublicationDate(new Date()); return book; }
}
运行之后,直接地址栏中访问 http://localhost:8080/book,即可看到返回的 JSON 数据。
- 转换集合数据
添加 getBooks() 方法,创建一个 List 集合,存放三本书。具体源码如下:
@RequestMapping(\\\”/getBooks\\\”)
public List getBooks() {
List<Book> bookList = new ArrayList<>();Book book1 = new Book();book1.setId(1);book1.setName(\\\"《码农翻身:用故事给技术加点料》\\\");book1.setAuthor(\\\"刘欣\\\");book1.setPrice(69f);book1.setBookPublicationDate(new Date());Book book2 = new Book();book2.setId(2);book2.setName(\\\"《漫画算法:小灰的算法之旅(全彩)》\\\");book2.setAuthor(\\\"魏梦舒\\\");book2.setPrice(79f);book2.setBookPublicationDate(new Date());Book book3 = new Book();book3.setId(3);book3.setName(\\\"《未来架构》\\\");book3.setAuthor(\\\"张亮\\\");book3.setPrice(99f);book3.setBookPublicationDate(new Date());bookList.add(book1);bookList.add(book2);bookList.add(book3);return bookList;List<Book> bookList = new ArrayList<>(); Book book1 = new Book(); book1.setId(1); book1.setName(\\\"《码农翻身:用故事给技术加点料》\\\"); book1.setAuthor(\\\"刘欣\\\"); book1.setPrice(69f); book1.setBookPublicationDate(new Date()); Book book2 = new Book(); book2.setId(2); book2.setName(\\\"《漫画算法:小灰的算法之旅(全彩)》\\\"); book2.setAuthor(\\\"魏梦舒\\\"); book2.setPrice(79f); book2.setBookPublicationDate(new Date()); Book book3 = new Book(); book3.setId(3); book3.setName(\\\"《未来架构》\\\"); book3.setAuthor(\\\"张亮\\\"); book3.setPrice(99f); book3.setBookPublicationDate(new Date()); bookList.add(book1); bookList.add(book2); bookList.add(book3); return bookList;
}
运行之后,直接地址栏中访问 http://localhost:8080/getBooks,即可看到 getBooks() 方法创建多个 Book 对象封装在 List 集合中并将 JSON 数据返回到客户端。
- 更换转换器
1)使用 Gson
Gson 是 Google 的开源 JSON 解析器,添加依赖的时候先要去除默认的 jackson,具体如下:
<groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><exclusion><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId></exclusion></exclusions><groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </exclusion> </exclusions>
<groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId>
在 Gson 转换时,如果需要格式化日期数据,则需要自定义 HttpMessageConverter,接着提供一个 GsonHttpMessageConverter 即可,具体如下:
@Configuration
public class GsonConfig {
@BeanGsonHttpMessageConverter gsonHttpMessageConverter() {GsonHttpMessageConverter converter = new GsonHttpMessageConverter();GsonBuilder builder = new GsonBuilder();builder.setDateFormat(\\\"yyyy-MM-dd\\\");builder.excludeFieldsWithModifiers(Modifier.PROTECTED);Gson gson = builder.create();converter.setGson(gson);return converter;}@Bean GsonHttpMessageConverter gsonHttpMessageConverter() { GsonHttpMessageConverter converter = new GsonHttpMessageConverter(); GsonBuilder builder = new GsonBuilder(); builder.setDateFormat(\\\"yyyy-MM-dd\\\"); builder.excludeFieldsWithModifiers(Modifier.PROTECTED); Gson gson = builder.create(); converter.setGson(gson); return converter; }
}
修改 Book 类,具体如下:
public class Book {
private Integer id;private String name;private String author;protected Float price;private Date bookPublicationDate;// getter 和 setter 方法private Integer id; private String name; private String author; protected Float price; private Date bookPublicationDate; // getter 和 setter 方法
}
运行之后,直接地址栏中访问 http://localhost:8080/getBooks,效果如图:
2)使用 fastjson
fastjson 是阿里巴巴的开源 JSON 解析器,也是目前速度最快的 JSON 解析器,整合之后需要提供相应的 HttpMessageConverter 才能使用,添加依赖,具体如下:
<groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><exclusion><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId></exclusion></exclusions><groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </exclusion> </exclusions>
<groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId>
接着,添加 fastjson 的 HttpMessageConverter,具体如下:
@Configuration
public class NXFastJsonConfig {
@BeanFastJsonHttpMessageConverter fastJsonHttpMessageConverter() {FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();FastJsonConfig config = new FastJsonConfig();config.setDateFormat(\\\"yyyy-MM-dd\\\");config.setCharset(Charset.forName(\\\"UTF-8\\\"));config.setSerializerFeatures(SerializerFeature.WriteClassName,SerializerFeature.WriteMapNullValue,SerializerFeature.PrettyFormat,SerializerFeature.WriteNullListAsEmpty,SerializerFeature.WriteNullStringAsEmpty);converter.setFastJsonConfig(config);return converter;}@Bean FastJsonHttpMessageConverter fastJsonHttpMessageConverter() { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); FastJsonConfig config = new FastJsonConfig(); config.setDateFormat(\\\"yyyy-MM-dd\\\"); config.setCharset(Charset.forName(\\\"UTF-8\\\")); config.setSerializerFeatures( SerializerFeature.WriteClassName, SerializerFeature.WriteMapNullValue, SerializerFeature.PrettyFormat, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty ); converter.setFastJsonConfig(config); return converter; }
}
再来 application.properties 中配置一个响应编码,具体如下:
spring.http.encoding.force-response=true
运行之后,直接地址栏中访问 http://localhost:8080/getBooks,效果如图:
本文来源于:奈学开发者社区-江帅帅
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
源码资源库 » 江帅帅:精通 Spring Boot 系列 05