当前位置:   article > 正文

SpringBoot整合Json(Fastjson、Gson)_springboot配置gson和fastjson共用

springboot配置gson和fastjson共用

SpringBoot整合Fastjson

pom.xml修改,排除默认Jackson,引入Fastjson

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. <exclusions>
  5. <exclusion>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-json</artifactId>
  8. </exclusion>
  9. </exclusions>
  10. </dependency>
  11. <dependency>
  12. <groupId>com.alibaba</groupId>
  13. <artifactId>fastjson</artifactId>
  14. <version>1.2.76</version>
  15. </dependency>

配置FastJsonHttpMessageConverter

  1. import com.alibaba.fastjson.serializer.SerializerFeature;
  2. import com.alibaba.fastjson.support.config.FastJsonConfig;
  3. import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import java.nio.charset.StandardCharsets;
  7. @Configuration
  8. public class WebConfiguration {
  9. @Bean
  10. FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
  11. FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
  12. // FastJson 配置
  13. FastJsonConfig config = new FastJsonConfig();
  14. config.setCharset(StandardCharsets.UTF_8);
  15. config.setDateFormat("yyyy-MM-dd");
  16. config.setSerializerFeatures(
  17. // 是否输出值为null的字段,默认为false,我们将它打开
  18. SerializerFeature.WriteMapNullValue,
  19. // 将Collection类型字段的字段空值输出为[]
  20. SerializerFeature.WriteNullListAsEmpty,
  21. // 将字符串类型字段的空值输出为空字符串
  22. SerializerFeature.WriteNullStringAsEmpty,
  23. // 将数值类型字段的空值输出为0
  24. SerializerFeature.WriteNullNumberAsZero,
  25. // 禁用循环引用
  26. SerializerFeature.DisableCircularReferenceDetect
  27. );
  28. converter.setFastJsonConfig(config);
  29. return converter;
  30. }
  31. }

以下配置参考:https://blog.csdn.net/u010246789/article/details/52539576

名称含义
QuoteFieldNames输出key时是否使用双引号,默认为true
UseSingleQuotes使用单引号而不是双引号,默认为false
WriteMapNullValue是否输出值为null的字段,默认为false
WriteEnumUsingToStringEnum输出name()或者original,默认为false
UseISO8601DateFormatDate使用ISO8601格式输出,默认为false
WriteNullListAsEmptyList字段如果为null,输出为[],而非null
WriteNullStringAsEmpty字符类型字段如果为null,输出为”“,而非null
WriteNullNumberAsZero数值字段如果为null,输出为0,而非null
WriteNullBooleanAsFalseBoolean字段如果为null,输出为false,而非null
SkipTransientField如果是true,类中的Get方法对应的Field是transient,序列化时将会被忽略。默认为true
SortField按字段名称排序后输出。默认为false
WriteTabAsSpecial把\t做转义输出,默认为false(不推荐
PrettyFormat结果是否格式化,默认为false
WriteClassName序列化时写入类型信息,默认为false。反序列化是需用到
DisableCircularReferenceDetect消除对同一对象循环引用的问题,默认为false
WriteSlashAsSpecial对斜杠’/’进行转义
BrowserCompatible将中文都会序列化为\uXXXX格式,字节数会多一些,但是能兼容IE 6,默认为false
WriteDateUseDateFormat全局修改日期格式,默认为false。JSON.DEFFAULT_DATE_FORMAT = “yyyy-MM-dd”;JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);
DisableCheckSpecialChar一个对象的字符串属性中如果有特殊字符如双引号,将会在转成json时带有反斜杠转移符。如果不需要转义,可以使用这个属性。默认为false
NotWriteRootClassName含义
BeanToArray将对象转为array输出
WriteNonStringKeyAsString含义
NotWriteDefaultValue含义
BrowserSecure含义
IgnoreNonFieldGetter含义
WriteEnumUsingName含义

SpringBoot整合Gson

pom.xml修改,排除默认Jackson,引入Gson:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. <exclusions>
  5. <exclusion>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-json</artifactId>
  8. </exclusion>
  9. </exclusions>
  10. </dependency>
  11. <dependency>
  12. <groupId>com.google.code.gson</groupId>
  13. <artifactId>gson</artifactId>
  14. </dependency>

Spring Boot 提供Gson的自动配置,如上引入Gson即可使用。

application.properties:

  1. # 序列化日期对象时使用的格式
  2. spring.gson.date-format=
  3. # 是否禁用HTML的转义字符(比如'<','>'等)
  4. spring.gson.disable-html-escaping=
  5. # 序列化时是否排除内部类
  6. spring.gson.disable-inner-class-serialization=
  7. # 序列化时是否启用复杂映射键
  8. spring.gson.enable-complex-map-key-serialization=
  9. # 序列化或反序列化时是否排除所有没有“@Expose”注解的字段。
  10. spring.gson.exclude-fields-without-expose-annotation=
  11. # 序列化时应用于对象字段的命名策略
  12. spring.gson.field-naming-policy=
  13. # 是否在输出之前添加一些特殊文本来生成不可执行的JSON
  14. spring.gson.generate-non-executable-json=
  15. # 是否放宽解析不符合RFC 4627的JSON
  16. spring.gson.lenient=
  17. # Long类型的序列化策略
  18. spring.gson.long-serialization-policy=
  19. # 序列化时是否输出经过美化后格式的JSON
  20. spring.gson.pretty-printing=
  21. # 是否序列化空字段(null)
  22. spring.gson.serialize-nulls=

附源码:

  1. /*
  2. * Copyright 2012-2019 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.springframework.boot.autoconfigure.http;
  17. import com.google.gson.Gson;
  18. import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
  19. import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
  20. import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
  21. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
  22. import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
  23. import org.springframework.boot.autoconfigure.condition.NoneNestedConditions;
  24. import org.springframework.context.annotation.Bean;
  25. import org.springframework.context.annotation.Conditional;
  26. import org.springframework.context.annotation.Configuration;
  27. import org.springframework.http.converter.json.GsonHttpMessageConverter;
  28. import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
  29. /**
  30. * Configuration for HTTP Message converters that use Gson.
  31. *
  32. * @author Andy Wilkinson
  33. * @author Eddú Meléndez
  34. */
  35. @Configuration(proxyBeanMethods = false)
  36. @ConditionalOnClass(Gson.class)
  37. class GsonHttpMessageConvertersConfiguration {
  38. @Configuration(proxyBeanMethods = false)
  39. @ConditionalOnBean(Gson.class)
  40. @Conditional(PreferGsonOrJacksonAndJsonbUnavailableCondition.class)
  41. static class GsonHttpMessageConverterConfiguration {
  42. @Bean
  43. @ConditionalOnMissingBean
  44. GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
  45. GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
  46. converter.setGson(gson);
  47. return converter;
  48. }
  49. }
  50. private static class PreferGsonOrJacksonAndJsonbUnavailableCondition extends AnyNestedCondition {
  51. PreferGsonOrJacksonAndJsonbUnavailableCondition() {
  52. super(ConfigurationPhase.REGISTER_BEAN);
  53. }
  54. @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY,
  55. havingValue = "gson")
  56. static class GsonPreferred {
  57. }
  58. @Conditional(JacksonAndJsonbUnavailableCondition.class)
  59. static class JacksonJsonbUnavailable {
  60. }
  61. }
  62. private static class JacksonAndJsonbUnavailableCondition extends NoneNestedConditions {
  63. JacksonAndJsonbUnavailableCondition() {
  64. super(ConfigurationPhase.REGISTER_BEAN);
  65. }
  66. @ConditionalOnBean(MappingJackson2HttpMessageConverter.class)
  67. static class JacksonAvailable {
  68. }
  69. @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY,
  70. havingValue = "jsonb")
  71. static class JsonbPreferred {
  72. }
  73. }
  74. }
  1. /*
  2. * Copyright 2012-2019 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.springframework.boot.autoconfigure.gson;
  17. import java.util.List;
  18. import com.google.gson.Gson;
  19. import com.google.gson.GsonBuilder;
  20. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  21. import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
  22. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
  23. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  24. import org.springframework.boot.context.properties.PropertyMapper;
  25. import org.springframework.context.annotation.Bean;
  26. import org.springframework.context.annotation.Configuration;
  27. import org.springframework.core.Ordered;
  28. /**
  29. * {@link EnableAutoConfiguration Auto-configuration} for Gson.
  30. *
  31. * @author David Liu
  32. * @author Ivan Golovko
  33. * @since 1.2.0
  34. */
  35. @Configuration(proxyBeanMethods = false)
  36. @ConditionalOnClass(Gson.class)
  37. @EnableConfigurationProperties(GsonProperties.class)
  38. public class GsonAutoConfiguration {
  39. @Bean
  40. @ConditionalOnMissingBean
  41. public GsonBuilder gsonBuilder(List<GsonBuilderCustomizer> customizers) {
  42. GsonBuilder builder = new GsonBuilder();
  43. customizers.forEach((c) -> c.customize(builder));
  44. return builder;
  45. }
  46. @Bean
  47. @ConditionalOnMissingBean
  48. public Gson gson(GsonBuilder gsonBuilder) {
  49. return gsonBuilder.create();
  50. }
  51. @Bean
  52. public StandardGsonBuilderCustomizer standardGsonBuilderCustomizer(GsonProperties gsonProperties) {
  53. return new StandardGsonBuilderCustomizer(gsonProperties);
  54. }
  55. static final class StandardGsonBuilderCustomizer implements GsonBuilderCustomizer, Ordered {
  56. private final GsonProperties properties;
  57. StandardGsonBuilderCustomizer(GsonProperties properties) {
  58. this.properties = properties;
  59. }
  60. @Override
  61. public int getOrder() {
  62. return 0;
  63. }
  64. @Override
  65. public void customize(GsonBuilder builder) {
  66. GsonProperties properties = this.properties;
  67. PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
  68. map.from(properties::getGenerateNonExecutableJson).toCall(builder::generateNonExecutableJson);
  69. map.from(properties::getExcludeFieldsWithoutExposeAnnotation)
  70. .toCall(builder::excludeFieldsWithoutExposeAnnotation);
  71. map.from(properties::getSerializeNulls).whenTrue().toCall(builder::serializeNulls);
  72. map.from(properties::getEnableComplexMapKeySerialization).toCall(builder::enableComplexMapKeySerialization);
  73. map.from(properties::getDisableInnerClassSerialization).toCall(builder::disableInnerClassSerialization);
  74. map.from(properties::getLongSerializationPolicy).to(builder::setLongSerializationPolicy);
  75. map.from(properties::getFieldNamingPolicy).to(builder::setFieldNamingPolicy);
  76. map.from(properties::getPrettyPrinting).toCall(builder::setPrettyPrinting);
  77. map.from(properties::getLenient).toCall(builder::setLenient);
  78. map.from(properties::getDisableHtmlEscaping).toCall(builder::disableHtmlEscaping);
  79. map.from(properties::getDateFormat).to(builder::setDateFormat);
  80. }
  81. }
  82. }

根据源码自定义Gson日期配置:

  1. import com.google.gson.Gson;
  2. import com.google.gson.GsonBuilder;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.http.converter.json.GsonHttpMessageConverter;
  6. @Configuration
  7. public class WebConfiguration {
  8. @Bean
  9. public GsonHttpMessageConverter gsonHttpMessageConverter() {
  10. GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
  11. GsonBuilder builder = new GsonBuilder();
  12. builder.setDateFormat("yyyy-MM-dd");
  13. Gson gson = builder.create();
  14. converter.setGson(gson);
  15. return converter;
  16. }
  17. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/1000735
推荐阅读
相关标签
  

闽ICP备14008679号