gpt4 book ai didi

java - Spring boot中如何配置gson?

转载 作者:行者123 更新时间:2023-12-02 08:39:30 24 4
gpt4 key购买 nike

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

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

最佳答案

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

关于java - Spring boot中如何配置gson?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61464046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com