如何使用谷歌Gson,而不是默认的春季杰克逊



我正在一个项目中工作,我想用Swagger来记录它。是一个使用Spring Boot实现的项目,我们使用库"com.google.code.gson"而不是默认的SpringBoot"Jackson",但使用gson Swagger不起作用。

问题在于回报模式。

Gson返回如下:

{"value":"{"swagger":"2.0","info":{"description":

Jackson返回如下:

{"swagger":"2.0","info":{"description"

有人知道我怎样才能让Gson作品吗?

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

这就是你所需要做的!

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

我们可以看到,它使用Jackson定义的注释@JsonRawValue来指示Jackson应该使用方法value()的返回值作为Json对象的序列化结果,但是Gson没有识别出这个注释,序列化结果变成

{
"value": "{"swagger":"2.0"...."
}

而不是正确的响应格式:

{
"swagger": "2.0",
"info":[...],
...
}

解决方案是为您的Gson-bean 定制TypeAdapterJsonSerializer

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

老问题,但这是我的解决方案,使用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);
}
}
}

我希望它对某人有用。

最新更新