How config gson in Spring boot?

强颜欢笑 提交于 2021-02-11 05:59:03

问题


Spring Boot 2

In application.yml

  http:
    converters:
      preferred-json-mapper: gson

Now I write class with custom settings for 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();
    }
}

How I can config Spring Boot with my custom Gson object from GsonUtil?


回答1:


You need to register org.springframework.http.converter.json.GsonHttpMessageConverter converter which handles serialisation and deserialisation behind the scene. You can do that in this way:

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));
    }
}

If you want to keep default list of converters you can also use extendMessageConverters method instead of configureMessageConverters.



来源:https://stackoverflow.com/questions/61464046/how-config-gson-in-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!