2

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

4

1 回答 1

3

您需要注册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));
    }
}

如果您想保留默认的转换器列表,您也可以使用extendMessageConvertersmethod 而不是configureMessageConverters.

于 2020-04-27T22:35:13.683 回答