Springboot整合Json(Jackson,Gson,FastJson)

我会带着你远行 2023-10-14 23:04 202阅读 0赞

文章目录

  • springboot整合json有三种方式,springboot默认是使用jackson的,如果要使用其他两种,要排除掉jackson
    • 1.springboot整合jackson
      • 1.1 pom.xml
      • 1.2 实体类,jackson注解的使用
      • 1.3 controller
      • 1.4 jackson全局配置
    • 2.springboot整合gson
      • 2.1 pom.xml
      • 2.2 实体类
      • 2.3 controller
      • 2.4 gson的全局配置方式
        • 2.4.1 application.[properties](https://so.csdn.net/so/search?q=properties&spm=1001.2101.3001.7020)
        • 2.4.2 通过配置文件,提供一个GsonBuilder或者转换器的Bean
    • 3.springboot整合fastjson
      • 3.1 pom.xml
      • 3.2 实体类
      • 3.3 controller
      • 3.4 fastjson的配置
    • 3.总结

springboot整合json有三种方式,springboot默认是使用jackson的,如果要使用其他两种,要排除掉jackson

1.springboot整合jackson

1.1 pom.xml

  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.5.4</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.yl</groupId>
  12. <artifactId>springbootjackson</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>springbootjackson</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-web</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-test</artifactId>
  27. <scope>test</scope>
  28. </dependency>
  29. </dependencies>
  30. <build>
  31. <plugins>
  32. <plugin>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-maven-plugin</artifactId>
  35. </plugin>
  36. </plugins>
  37. </build>
  38. </project>

1.2 实体类,jackson注解的使用

  1. package com.yl.springbootjackson.model;
  2. import com.fasterxml.jackson.annotation.*;
  3. import java.util.Date;
  4. //序列化/反序列化时批量忽略属性
  5. @JsonIgnoreProperties({
  6. "score","message"})
  7. public class User {
  8. @JsonProperty(index = 92)
  9. private String name;
  10. //序列化/反序列化时忽略某一个属性
  11. @JsonIgnore
  12. private Integer sex;
  13. //指定属性序列化/反序列化时的名称,默认就是属性名,value指定新的属性名,index主要用于排序
  14. @JsonProperty(value = "aage",index = 91)
  15. //类似于JsonProperty中的index,用于排序
  16. //@JsonPropertyOrder()
  17. private int age;
  18. @JsonProperty(index = 90)
  19. //日期格式化,注意时区问题
  20. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "Asia/Shanghai")
  21. private Date birth;
  22. @JsonProperty(index = 89)
  23. private Integer score;
  24. @JsonProperty(index = 88)
  25. private String message;
  26. public String getName() {
  27. return name;
  28. }
  29. public void setName(String name) {
  30. this.name = name;
  31. }
  32. public int getAge() {
  33. return age;
  34. }
  35. public void setAge(int age) {
  36. this.age = age;
  37. }
  38. public Date getBirth() {
  39. return birth;
  40. }
  41. public void setBirth(Date birth) {
  42. this.birth = birth;
  43. }
  44. @Override
  45. public String toString() {
  46. return "User{" +
  47. "name='" + name + '\'' +
  48. ", age=" + age +
  49. ", birth=" + birth +
  50. '}';
  51. }
  52. }

1.3 controller

  1. package com.yl.springbootjackson.controller;
  2. import com.yl.springbootjackson.model.User;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.PostMapping;
  5. import org.springframework.web.bind.annotation.RequestBody;
  6. import org.springframework.web.bind.annotation.RestController;
  7. import java.util.Date;
  8. @RestController
  9. public class UserController {
  10. @GetMapping("/getUser")
  11. public User getUser() {
  12. User user = new User();
  13. user.setName("小兰");
  14. user.setAge(19);
  15. user.setBirth(new Date());
  16. return user;
  17. }
  18. @PostMapping("/save")
  19. public void save(@RequestBody User user) {
  20. System.out.println(user);
  21. }
  22. }

1.4 jackson全局配置

  1. package com.yl.springbootjackson.config;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import java.text.SimpleDateFormat;
  6. /**
  7. * jackson全局配置方式,注入ObjectMapper即可
  8. */
  9. @Configuration
  10. public class WebMVCConfig {
  11. @Bean
  12. ObjectMapper objectMapper() {
  13. ObjectMapper objectMapper = new ObjectMapper();
  14. objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
  15. return objectMapper;
  16. }
  17. }

2.springboot整合gson

2.1 pom.xml

  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.5.4</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.yl</groupId>
  12. <artifactId>springbootgson</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>springbootgson</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-web</artifactId>
  23. <!--排除jackson依赖-->
  24. <exclusions>
  25. <exclusion>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-json</artifactId>
  28. </exclusion>
  29. </exclusions>
  30. </dependency>
  31. <!--gson依赖-->
  32. <dependency>
  33. <groupId>com.google.code.gson</groupId>
  34. <artifactId>gson</artifactId>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-starter-test</artifactId>
  39. <scope>test</scope>
  40. </dependency>
  41. </dependencies>
  42. <build>
  43. <plugins>
  44. <plugin>
  45. <groupId>org.springframework.boot</groupId>
  46. <artifactId>spring-boot-maven-plugin</artifactId>
  47. </plugin>
  48. </plugins>
  49. </build>
  50. </project>

2.2 实体类

  1. package com.yl.springbootgson.model;
  2. import com.google.gson.annotations.Expose;
  3. import java.util.Date;
  4. public class User {
  5. @Expose
  6. private String name;
  7. @Expose
  8. private Date birth;
  9. public String getName() {
  10. return name;
  11. }
  12. public void setName(String name) {
  13. this.name = name;
  14. }
  15. public Date getBirth() {
  16. return birth;
  17. }
  18. public void setBirth(Date birth) {
  19. this.birth = birth;
  20. }
  21. }

2.3 controller

  1. package com.yl.springbootgson.controller;
  2. import com.yl.springbootgson.model.User;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. import java.util.Date;
  6. @RestController
  7. public class UserController {
  8. @GetMapping("/getUser")
  9. public User getUser() {
  10. User user = new User();
  11. user.setName("小南");
  12. user.setBirth(new Date());
  13. return user;
  14. }
  15. }

2.4 gson的全局配置方式

2.4.1 application.properties
  1. spring.gson.date-format=yyyy-MM-dd HH:mm:ss
  2. # 是否禁用HTML的转义字符
  3. spring.gson.disable-html-escaping=true
  4. # 序列化时是否排除内部类
  5. spring.gson.disable-inner-class-serialization=false
  6. # 序列化时是否弃用复杂映射键
  7. spring.gson.enable-complex-map-key-serialization=
  8. # 是否排除没有@Expose注解的字段
  9. spring.gson.exclude-fields-without-expose-annotation=true
  10. # 序列化时字段名的命名策略
  11. spring.gson.field-naming-policy=lower_case_with_underscores
  12. # 在输出之前添加一些特殊的的文本来生成一个不可执行的json
  13. spring.gson.generate-non-executable-json=
  14. # 是否序列化空字段
  15. spring.gson.serialize-nulls=false
2.4.2 通过配置文件,提供一个GsonBuilder或者转换器的Bean
  1. package com.yl.springbootgson.config;
  2. import com.google.gson.GsonBuilder;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. /**
  6. * 自定义一个GsonBuilder,配置一些gson的属性
  7. */
  8. @Configuration
  9. public class WebMVCConfig {
  10. @Bean
  11. GsonBuilder gsonBuilder() {
  12. GsonBuilder gsonBuilder = new GsonBuilder();
  13. gsonBuilder.setDateFormat("yyyy-MM-dd");
  14. return gsonBuilder;
  15. }
  16. }

3.springboot整合fastjson

3.1 pom.xml

  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.5.4</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.yl</groupId>
  12. <artifactId>fastjson</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>fastjson</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-web</artifactId>
  23. <exclusions>
  24. <exclusion>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-json</artifactId>
  27. </exclusion>
  28. </exclusions>
  29. </dependency>
  30. <!--fastjson依赖-->
  31. <dependency>
  32. <groupId>com.alibaba</groupId>
  33. <artifactId>fastjson</artifactId>
  34. <version>1.2.75</version>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-starter-test</artifactId>
  39. <scope>test</scope>
  40. </dependency>
  41. </dependencies>
  42. <build>
  43. <plugins>
  44. <plugin>
  45. <groupId>org.springframework.boot</groupId>
  46. <artifactId>spring-boot-maven-plugin</artifactId>
  47. </plugin>
  48. </plugins>
  49. </build>
  50. </project>

3.2 实体类

  1. package com.yl.fastjson.model;
  2. import java.util.Date;
  3. public class User {
  4. private String name;
  5. private Date birth;
  6. private Integer sex;
  7. public String getName() {
  8. return name;
  9. }
  10. public void setName(String name) {
  11. this.name = name;
  12. }
  13. public Date getBirth() {
  14. return birth;
  15. }
  16. public void setBirth(Date birth) {
  17. this.birth = birth;
  18. }
  19. public Integer getSex() {
  20. return sex;
  21. }
  22. public void setSex(Integer sex) {
  23. this.sex = sex;
  24. }
  25. }

3.3 controller

  1. package com.yl.fastjson.controller;
  2. import com.yl.fastjson.model.User;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. import java.util.Date;
  6. @RestController
  7. public class UserController {
  8. @GetMapping("/getUser")
  9. public User user() {
  10. User user = new User();
  11. user.setName("小白");
  12. user.setBirth(new Date());
  13. user.setSex(0);
  14. return user;
  15. }
  16. }

3.4 fastjson的配置

  1. package com.yl.fastjson.config;
  2. import com.alibaba.fastjson.serializer.SerializerFeature;
  3. import com.alibaba.fastjson.support.config.FastJsonConfig;
  4. import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.http.MediaType;
  8. import org.springframework.http.converter.HttpMessageConverter;
  9. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  10. import java.nio.charset.Charset;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. /**
  14. * fastjson如果想要使用,必须提供一个Converter
  15. */
  16. @Configuration
  17. public class WebMvcConfig implements WebMvcConfigurer {
  18. //方式一:继承WebMvcConfigurer,重写configureMessageConverters,将converter添加到converters中
  19. @Override
  20. public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
  21. FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
  22. List supportedMediaTypes = new ArrayList<>();
  23. supportedMediaTypes.add(MediaType.APPLICATION_JSON);
  24. supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
  25. supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
  26. supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
  27. supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
  28. supportedMediaTypes.add(MediaType.APPLICATION_PDF);
  29. supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
  30. supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
  31. supportedMediaTypes.add(MediaType.APPLICATION_XML);
  32. supportedMediaTypes.add(MediaType.IMAGE_GIF);
  33. supportedMediaTypes.add(MediaType.IMAGE_JPEG);
  34. supportedMediaTypes.add(MediaType.IMAGE_PNG);
  35. supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
  36. supportedMediaTypes.add(MediaType.TEXT_HTML);
  37. supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
  38. supportedMediaTypes.add(MediaType.TEXT_PLAIN);
  39. supportedMediaTypes.add(MediaType.TEXT_XML);
  40. converter.setSupportedMediaTypes(supportedMediaTypes);
  41. FastJsonConfig config = converter.getFastJsonConfig();
  42. config.setCharset(Charset.forName("UTF-8"));
  43. config.setDateFormat("yyyy-MM-dd HH:mm:ss");
  44. config.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteClassName);
  45. converter.setFastJsonConfig(config);
  46. converter.setDefaultCharset(Charset.forName("UTF-8"));
  47. converters.add(converter);
  48. }
  49. //方式二:注册一个Bean
  50. // @Bean
  51. // FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
  52. // FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
  53. // List supportedMediaTypes = new ArrayList<>();
  54. // supportedMediaTypes.add(MediaType.APPLICATION_JSON);
  55. // supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
  56. // supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
  57. // supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
  58. // supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
  59. // supportedMediaTypes.add(MediaType.APPLICATION_PDF);
  60. // supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
  61. // supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
  62. // supportedMediaTypes.add(MediaType.APPLICATION_XML);
  63. // supportedMediaTypes.add(MediaType.IMAGE_GIF);
  64. // supportedMediaTypes.add(MediaType.IMAGE_JPEG);
  65. // supportedMediaTypes.add(MediaType.IMAGE_PNG);
  66. // supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
  67. // supportedMediaTypes.add(MediaType.TEXT_HTML);
  68. // supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
  69. // supportedMediaTypes.add(MediaType.TEXT_PLAIN);
  70. // supportedMediaTypes.add(MediaType.TEXT_XML);
  71. // converter.setSupportedMediaTypes(supportedMediaTypes);
  72. // FastJsonConfig config = converter.getFastJsonConfig();
  73. // config.setCharset(Charset.forName("UTF-8"));
  74. // config.setDateFormat("yyyy-MM-dd HH:mm:ss");
  75. // config.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteClassName);
  76. // converter.setFastJsonConfig(config);
  77. // converter.setDefaultCharset(Charset.forName("UTF-8"));
  78. // return converter;
  79. // }
  80. }

3.总结

3.1springboot默认是使用jackson的,对jackson和gson都做了自动配置,所以一般使用这两者之一即可。如果非得要fastjson,那么必须将FastJsonHttpMessageConverter注册到容器中或者实现WebMvcConfigurer接口重写configureMessageConverters方法,将FastJsonHttpMessageConverter对象加到converters集合中即可。
3.2 除此之外,我们也可以自定义jackson或者gson的转换器,然后在里面设置一些自己需要的属性,然后注册到容器中即可使用

发表评论

表情:
评论列表 (有 0 条评论,202人围观)

还没有评论,来说两句吧...

相关阅读