如何在春季启动时配置gson?

时间:2020-04-27 16:50:20

标签: java spring spring-boot gson http-message-converter

Spring Boot 2

在application.yml

  http:
    converters:
      preferred-json-mapper: gson

现在,我用Gson的自定义设置编写课程:

public class GsonUtil {
    public static GsonBuilder gsonbuilder = new GsonBuilder();
    public static Gson gson;
    public static JsonParser parser = new JsonParser();

    static {
        // @Exclude -> to exclude specific field when serialize/deserilaize
        gsonbuilder.addSerializationExclusionStrategy(new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes field) {
                return field.getAnnotation(Exclude.class) != null;
            }

            @Override
            public boolean shouldSkipClass(Class<?> clazz) {
                return false;
            }
        });
        gsonbuilder.setPrettyPrinting();
        gson = gsonbuilder.create();
    }
}

如何使用Spring Boot中的自定义Gson对象配置GsonUtil

1 个答案:

答案 0 :(得分:1)

您需要注册org.springframework.http.converter.json.GsonHttpMessageConverter转换器,该转换器可以在后台处理序列化和反序列化。您可以通过以下方式做到这一点:

import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //You can provide your custom `Gson` object.
        converters.add(new GsonHttpMessageConverter(GsonUtil.gson));
    }
}

如果要保留默认的转换器列表,也可以使用extendMessageConverters方法代替configureMessageConverters