How config gson in Spring boot?

1.7k Views Asked by At

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

There are 1 best solutions below

0
On

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.