Swagger constructs it's own Json
class to communicate with frontend (see springfox.documentation.spring.web.json.Json
), which is defined as follow:
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;
}
}
We can see that it use annotation @JsonRawValue
defined by Jackson to indicate that Jackson should use the return value of the method value()
as serializing result of Json
object, however, this annotation is not recognized by Gson, and serialized result becomes
{
"value": "{\"swagger\":\"2.0\"...."
}
instead of the correct response format:
{
"swagger": "2.0",
"info":[...],
...
}
the solution is customize a TypeAdapter
or JsonSerializer
for your Gson bean
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());
}
}
}