3 回答
TA贡献1891条经验 获得超3个赞
Spring Boot 默认使用 Jackson 来序列化和反序列化 REST API 中的请求和响应对象。如果您想使用 GSON 而不是 Jackson,那么您可以在 pom.xml 或 build.gradle 文件中添加 Gson 依赖项,并在 application.properties 文件中指定一个属性来告诉 Spring Boot 使用 Gson 作为您首选的 json 映射器。
# Preferred JSON mapper to use for HTTP message conversion.
spring.http.converters.preferred-json-mapper=gson
这就是你需要做的!
TA贡献1869条经验 获得超4个赞
老问题,但这是我的解决方案,使用 Spring Boot + OpenAPI + Swagger + Gson:
配置组件:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.acepta.signerservices.core.gson.SwaggerJsonSerializer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@Configuration
public class GsonConfiguration {
@Bean
public Gson gson() {
return new GsonBuilder()
.registerTypeAdapter(String.class, new SwaggerJsonSerializer())
.create();
}
}
Gson 适配器:
import java.lang.reflect.Type;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class SwaggerJsonSerializer implements JsonSerializer<String> {
@Override
public JsonElement serialize(String json, Type typeOfSrc, JsonSerializationContext context) {
if (json.contains("openapi")) {
return JsonParser.parseString(json.replace("\r", ""));
} else {
return new Gson().toJsonTree(json, typeOfSrc);
}
}
}
我希望它对某人有用。
TA贡献1797条经验 获得超6个赞
Swagger 构建了自己的Json类来与前端进行通信(请参阅 参考资料springfox.documentation.spring.web.json.Json),其定义如下:
import com.fasterxml.jackson.annotation.JsonRawValue;
import com.fasterxml.jackson.annotation.JsonValue;
public class Json {
private final String value;
public Json(String value) {
this.value = value;
}
@JsonValue. // NOTICE THIS
@JsonRawValue // NOTICE THIS
public String value() {
return value;
}
}
我们可以看到它使用@JsonRawValueJackson定义的注解来表示Jackson应该使用方法的返回值value()作为Json对象的序列化结果,但是这个注解不被Gson识别,序列化结果变成
{
"value": "{\"swagger\":\"2.0\"...."
}
而不是正确的响应格式:
{
"swagger": "2.0",
"info":[...],
...
}
解决方案是为您的 Gson bean定制一个TypeAdapter或JsonSerializer
import com.google.gson.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.spring.web.json.Json;
@Configuration
public class GsonConfig {
@Bean
public Gson gson() {
return new GsonBuilder()
.registerTypeAdapter(Json.class, new SwaggerJsonTypeAdapter())
.create();
}
public static class SwaggerJsonTypeAdapter implements JsonSerializer<Json> {
@Override
public JsonElement serialize(Json json, Type type, JsonSerializationContext context) {
return JsonParser.parseString(json.value());
}
}
}
添加回答
举报
