Как конфиг gson в Spring загрузить? - PullRequest
0 голосов
/ 27 апреля 2020

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 Ответ

2 голосов
/ 28 апреля 2020

Вам необходимо зарегистрировать 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.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...