赞
踩
SpringBoot整合Fastjson:
pom.xml修改,排除默认Jackson,引入Fastjson:
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- <exclusions>
- <exclusion>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-json</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>fastjson</artifactId>
- <version>1.2.76</version>
- </dependency>
配置FastJsonHttpMessageConverter
- import com.alibaba.fastjson.serializer.SerializerFeature;
- import com.alibaba.fastjson.support.config.FastJsonConfig;
- import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
- import java.nio.charset.StandardCharsets;
-
- @Configuration
- public class WebConfiguration {
-
- @Bean
- FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
- FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
- // FastJson 配置
- FastJsonConfig config = new FastJsonConfig();
- config.setCharset(StandardCharsets.UTF_8);
- config.setDateFormat("yyyy-MM-dd");
- config.setSerializerFeatures(
- // 是否输出值为null的字段,默认为false,我们将它打开
- SerializerFeature.WriteMapNullValue,
- // 将Collection类型字段的字段空值输出为[]
- SerializerFeature.WriteNullListAsEmpty,
- // 将字符串类型字段的空值输出为空字符串
- SerializerFeature.WriteNullStringAsEmpty,
- // 将数值类型字段的空值输出为0
- SerializerFeature.WriteNullNumberAsZero,
- // 禁用循环引用
- SerializerFeature.DisableCircularReferenceDetect
- );
- converter.setFastJsonConfig(config);
- return converter;
- }
- }
以下配置参考:https://blog.csdn.net/u010246789/article/details/52539576
名称 | 含义 |
QuoteFieldNames | 输出key时是否使用双引号,默认为true |
UseSingleQuotes | 使用单引号而不是双引号,默认为false |
WriteMapNullValue | 是否输出值为null的字段,默认为false |
WriteEnumUsingToString | Enum输出name()或者original,默认为false |
UseISO8601DateFormat | Date使用ISO8601格式输出,默认为false |
WriteNullListAsEmpty | List字段如果为null,输出为[],而非null |
WriteNullStringAsEmpty | 字符类型字段如果为null,输出为”“,而非null |
WriteNullNumberAsZero | 数值字段如果为null,输出为0,而非null |
WriteNullBooleanAsFalse | Boolean字段如果为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:
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- <exclusions>
- <exclusion>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-json</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- </dependency>
Spring Boot 提供Gson的自动配置,如上引入Gson即可使用。
application.properties:
- # 序列化日期对象时使用的格式
- spring.gson.date-format=
- # 是否禁用HTML的转义字符(比如'<','>'等)
- spring.gson.disable-html-escaping=
- # 序列化时是否排除内部类
- spring.gson.disable-inner-class-serialization=
- # 序列化时是否启用复杂映射键
- spring.gson.enable-complex-map-key-serialization=
- # 序列化或反序列化时是否排除所有没有“@Expose”注解的字段。
- spring.gson.exclude-fields-without-expose-annotation=
- # 序列化时应用于对象字段的命名策略
- spring.gson.field-naming-policy=
- # 是否在输出之前添加一些特殊文本来生成不可执行的JSON
- spring.gson.generate-non-executable-json=
- # 是否放宽解析不符合RFC 4627的JSON
- spring.gson.lenient=
- # Long类型的序列化策略
- spring.gson.long-serialization-policy=
- # 序列化时是否输出经过美化后格式的JSON
- spring.gson.pretty-printing=
- # 是否序列化空字段(null)
- spring.gson.serialize-nulls=
附源码:
- /*
- * Copyright 2012-2019 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
- package org.springframework.boot.autoconfigure.http;
-
- import com.google.gson.Gson;
-
- import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
- import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
- import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
- import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
- import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
- import org.springframework.boot.autoconfigure.condition.NoneNestedConditions;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Conditional;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.http.converter.json.GsonHttpMessageConverter;
- import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
-
- /**
- * Configuration for HTTP Message converters that use Gson.
- *
- * @author Andy Wilkinson
- * @author Eddú Meléndez
- */
- @Configuration(proxyBeanMethods = false)
- @ConditionalOnClass(Gson.class)
- class GsonHttpMessageConvertersConfiguration {
-
- @Configuration(proxyBeanMethods = false)
- @ConditionalOnBean(Gson.class)
- @Conditional(PreferGsonOrJacksonAndJsonbUnavailableCondition.class)
- static class GsonHttpMessageConverterConfiguration {
-
- @Bean
- @ConditionalOnMissingBean
- GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
- GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
- converter.setGson(gson);
- return converter;
- }
-
- }
-
- private static class PreferGsonOrJacksonAndJsonbUnavailableCondition extends AnyNestedCondition {
-
- PreferGsonOrJacksonAndJsonbUnavailableCondition() {
- super(ConfigurationPhase.REGISTER_BEAN);
- }
-
- @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY,
- havingValue = "gson")
- static class GsonPreferred {
-
- }
-
- @Conditional(JacksonAndJsonbUnavailableCondition.class)
- static class JacksonJsonbUnavailable {
-
- }
-
- }
-
- private static class JacksonAndJsonbUnavailableCondition extends NoneNestedConditions {
-
- JacksonAndJsonbUnavailableCondition() {
- super(ConfigurationPhase.REGISTER_BEAN);
- }
-
- @ConditionalOnBean(MappingJackson2HttpMessageConverter.class)
- static class JacksonAvailable {
-
- }
-
- @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY,
- havingValue = "jsonb")
- static class JsonbPreferred {
-
- }
-
- }
-
- }
- /*
- * Copyright 2012-2019 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
- package org.springframework.boot.autoconfigure.gson;
-
- import java.util.List;
-
- import com.google.gson.Gson;
- import com.google.gson.GsonBuilder;
-
- import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
- import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
- import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
- import org.springframework.boot.context.properties.EnableConfigurationProperties;
- import org.springframework.boot.context.properties.PropertyMapper;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.core.Ordered;
-
- /**
- * {@link EnableAutoConfiguration Auto-configuration} for Gson.
- *
- * @author David Liu
- * @author Ivan Golovko
- * @since 1.2.0
- */
- @Configuration(proxyBeanMethods = false)
- @ConditionalOnClass(Gson.class)
- @EnableConfigurationProperties(GsonProperties.class)
- public class GsonAutoConfiguration {
-
- @Bean
- @ConditionalOnMissingBean
- public GsonBuilder gsonBuilder(List<GsonBuilderCustomizer> customizers) {
- GsonBuilder builder = new GsonBuilder();
- customizers.forEach((c) -> c.customize(builder));
- return builder;
- }
-
- @Bean
- @ConditionalOnMissingBean
- public Gson gson(GsonBuilder gsonBuilder) {
- return gsonBuilder.create();
- }
-
- @Bean
- public StandardGsonBuilderCustomizer standardGsonBuilderCustomizer(GsonProperties gsonProperties) {
- return new StandardGsonBuilderCustomizer(gsonProperties);
- }
-
- static final class StandardGsonBuilderCustomizer implements GsonBuilderCustomizer, Ordered {
-
- private final GsonProperties properties;
-
- StandardGsonBuilderCustomizer(GsonProperties properties) {
- this.properties = properties;
- }
-
- @Override
- public int getOrder() {
- return 0;
- }
-
- @Override
- public void customize(GsonBuilder builder) {
- GsonProperties properties = this.properties;
- PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
- map.from(properties::getGenerateNonExecutableJson).toCall(builder::generateNonExecutableJson);
- map.from(properties::getExcludeFieldsWithoutExposeAnnotation)
- .toCall(builder::excludeFieldsWithoutExposeAnnotation);
- map.from(properties::getSerializeNulls).whenTrue().toCall(builder::serializeNulls);
- map.from(properties::getEnableComplexMapKeySerialization).toCall(builder::enableComplexMapKeySerialization);
- map.from(properties::getDisableInnerClassSerialization).toCall(builder::disableInnerClassSerialization);
- map.from(properties::getLongSerializationPolicy).to(builder::setLongSerializationPolicy);
- map.from(properties::getFieldNamingPolicy).to(builder::setFieldNamingPolicy);
- map.from(properties::getPrettyPrinting).toCall(builder::setPrettyPrinting);
- map.from(properties::getLenient).toCall(builder::setLenient);
- map.from(properties::getDisableHtmlEscaping).toCall(builder::disableHtmlEscaping);
- map.from(properties::getDateFormat).to(builder::setDateFormat);
- }
-
- }
-
- }
根据源码自定义Gson日期配置:
- import com.google.gson.Gson;
- import com.google.gson.GsonBuilder;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.http.converter.json.GsonHttpMessageConverter;
-
- @Configuration
- public class WebConfiguration {
-
- @Bean
- public GsonHttpMessageConverter gsonHttpMessageConverter() {
- GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
- GsonBuilder builder = new GsonBuilder();
- builder.setDateFormat("yyyy-MM-dd");
- Gson gson = builder.create();
- converter.setGson(gson);
- return converter;
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。