使用spring boot开发时java对象和Json对象转换的问题

时间:2021-07-24 09:34:01

java对象转换为json对象,市面上有很多第三方jar包,如下:

jackson(最常用)

  1. <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
  2. <dependency>
  3. <groupId>com.fasterxml.jackson.core</groupId>
  4. <artifactId>jackson-databind</artifactId>
  5. <version>2.11.2</version>
  6. </dependency>

gson

  1. <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
  2. <dependency>
  3. <groupId>com.google.code.gson</groupId>
  4. <artifactId>gson</artifactId>
  5. <version>2.8.5</version>
  6. </dependency>

fastjson

  1. <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>fastjson</artifactId>
  5. <version>1.2.62</version>
  6. </dependency>

一、构建测试项目

开发工具为:IDEA
后端技术:Spring boot ,Maven

引入依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.4.3</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.example</groupId>
  12. <artifactId>json</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>json</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-web</artifactId>
  27. </dependency>
  28.  
  29. <dependency>
  30. <groupId>org.projectlombok</groupId>
  31. <artifactId>lombok</artifactId>
  32. <optional>true</optional>
  33. </dependency>
  34. <dependency>
  35. <groupId>org.springframework.boot</groupId>
  36. <artifactId>spring-boot-starter-test</artifactId>
  37. <scope>test</scope>
  38. </dependency>
  39. </dependencies>
  40.  
  41. <build>
  42. <plugins>
  43. <plugin>
  44. <groupId>org.springframework.boot</groupId>
  45. <artifactId>spring-boot-maven-plugin</artifactId>
  46. <configuration>
  47. <excludes>
  48. <exclude>
  49. <groupId>org.projectlombok</groupId>
  50. <artifactId>lombok</artifactId>
  51. </exclude>
  52. </excludes>
  53. </configuration>
  54. </plugin>
  55. </plugins>
  56. </build>
  57.  
  58. </project>

可以从上面看出,并未引入Jackson相关依赖,这是因为Spring boot的起步依赖spring-boot-starter-web 已经为我们传递依赖了Jackson JSON库。

使用spring boot开发时java对象和Json对象转换的问题

当我们不用它,而采用其他第三方jar包时,我们可以排除掉它的依赖,可以为我们的项目瘦身。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. <exclusions>
  5. <exclusion>
  6. <artifactId>jackson-core</artifactId>
  7. <groupId>com.fasterxml.jackson.core</groupId>
  8. </exclusion>
  9. </exclusions>
  10. </dependency>

二、jackson转换

1.构建User实体类

  1. import lombok.AllArgsConstructor;
  2. import lombok.Data;
  3. import lombok.NoArgsConstructor;
  4.  
  5. @Data
  6. @NoArgsConstructor
  7. @AllArgsConstructor
  8. public class UserEntity {
  9.  
  10. private String userName;
  11.  
  12. private int age;
  13.  
  14. private String sex;
  15.  
  16. }

代码如下(示例):

  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. import seaborn as sns
  5. import warnings
  6. warnings.filterwarnings('ignore')
  7. import ssl
  8. ssl._create_default_https_context = ssl._create_unverified_context

2.controller类

Java对象转换为json对象

  1. @Controller
  2. public class JsonController {
  3.  
  4. @GetMapping("/json1")
  5. //思考问题,正常返回它会走视图解析器,而json需要返回的是一个字符串
  6. //市面上有很多的第三方jar包可以实现这个功能,jackson,只需要一个简单的注解就可以实现了
  7. //@ResponseBody,将服务器端返回的对象转换为json对象响应回去
  8. @ResponseBody
  9. public String json1() throws JsonProcessingException {
  10. //需要一个jackson的对象映射器,就是一个类,使用它可以将对象直接转换成json字符串
  11. ObjectMapper mapper = new ObjectMapper();
  12. //创建对象
  13. UserEntity userEntity = new UserEntity("笨笨熊", 18, "男");
  14. System.out.println(userEntity);
  15. //将java对象转换为json字符串
  16. String str = mapper.writeValueAsString(userEntity);
  17. System.out.println(str);
  18. //由于使用了@ResponseBody注解,这里会将str以json格式的字符串返回。
  19. return str;
  20. }
  21.  
  22. @GetMapping("/json2")
  23. @ResponseBody
  24. public String json2() throws JsonProcessingException {
  25.  
  26. ArrayList<UserEntity> userEntities = new ArrayList<>();
  27.  
  28. UserEntity user1 = new UserEntity("笨笨熊", 18, "男");
  29. UserEntity user2 = new UserEntity("笨笨熊", 18, "男");
  30. UserEntity user3 = new UserEntity("笨笨熊", 18, "男");
  31.  
  32. userEntities.add(user1);
  33. userEntities.add(user2);
  34. userEntities.add(user3);
  35.  
  36. return new ObjectMapper().writeValueAsString(userEntities);
  37. }
  38. }

Date对象转换为json对象

  1. @GetMapping("/json3")
  2. @ResponseBody
  3. public String json3() throws JsonProcessingException {
  4. ObjectMapper mapper = new ObjectMapper();
  5. //Date默认返回时间戳,所以需要关闭它的时间戳功能
  6. mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
  7. //时间格式化问题 自定义时间格式对象
  8. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  9. //让mapper指定时间日期格式为simpleDateFormat
  10. mapper.setDateFormat(simpleDateFormat);
  11. //写一个时间对象
  12. Date date = new Date();
  13. return mapper.writeValueAsString(date);
  14.  
  15. }

提取工具类JsonUtils

  1. public class JsonUtils {
  2.  
  3. public static String getJson(Object object){
  4. return getJson(object,"yyyy-MM-dd HH:mm:ss");
  5. }
  6. public static String getJson(Object object,String dateFormat) {
  7. ObjectMapper mapper = new ObjectMapper();
  8. //Date默认返回时间戳,所以需要关闭它的时间戳功能
  9. mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
  10. //时间格式化问题 自定义时间格式对象
  11. SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
  12. //让mapper指定时间日期格式为simpleDateFormat
  13. mapper.setDateFormat(simpleDateFormat);
  14. try{
  15. return mapper.writeValueAsString(object);
  16. }catch (JsonProcessingException e){
  17. e.printStackTrace();
  18. }
  19. return null;
  20. }
  21. }

优化后:

  1. @GetMapping("/json4")
  2. @ResponseBody
  3. public String json4() throws JsonProcessingException {
  4. Date date = new Date();
  5. return JsonUtils.getJson(date);
  6.  
  7. }

三、gson转换

引入上述gson依赖

Controller类

  1. @RestController
  2. public class gsonController {
  3. @GetMapping("/gson1")
  4. public String json1() throws JsonProcessingException {
  5.  
  6. ArrayList<UserEntity> userEntities = new ArrayList<>();
  7.  
  8. UserEntity user1 = new UserEntity("笨笨熊", 18, "男");
  9. UserEntity user2 = new UserEntity("笨笨熊", 18, "男");
  10. UserEntity user3 = new UserEntity("笨笨熊", 18, "男");
  11.  
  12. userEntities.add(user1);
  13. userEntities.add(user2);
  14. userEntities.add(user3);
  15.  
  16. Gson gson = new Gson();
  17. String str = gson.toJson(userEntities);
  18.  
  19. return str;
  20. }
  21. }

四、fastjson转换

引入相关依赖

Controller类

  1. @RestController
  2. public class FastJsonController {
  3. @GetMapping("/fastjson1")
  4. public String json1() throws JsonProcessingException {
  5.  
  6. ArrayList<UserEntity> userEntities = new ArrayList<>();
  7.  
  8. UserEntity user1 = new UserEntity("笨笨熊", 18, "男");
  9. UserEntity user2 = new UserEntity("笨笨熊", 18, "男");
  10. UserEntity user3 = new UserEntity("笨笨熊", 18, "男");
  11.  
  12. userEntities.add(user1);
  13. userEntities.add(user2);
  14. userEntities.add(user3);
  15.  
  16. String str = JSON.toJSONString(userEntities);
  17.  
  18. return str;
  19. }
  20. }

到此这篇关于使用spring boot开发时java对象和Json对象转换的问题的文章就介绍到这了,更多相关spring boot java对象和Json对象转换内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/BBQ__ZXB/article/details/114264184