我正在尝试构建一个 spring-boot (v1.2.3) 应用程序并使用 SpringFox(swagger2) v2.0.0 公开我的 Rest API
我的 Swagger Spring 配置
@EnableSwagger2
@Configuration
public class SwaggerConfig {
@Bean
public Docket myApi() {
return new Docket(DocumentationType.SWAGGER_2)
.genericModelSubstitutes(DeferredResult.class)
.useDefaultResponseMessages(false)
.forCodeGeneration(false)
.pathMapping("/my-prj");
}
}
我需要使用 gson 将我的 pojo 转换为 json,我这样做:
@Configuration
public class GsonHttpMessageConverterConfig {
@Bean
public GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
converter.setGson(gson);
return converter;
}
}
麻烦的是,如果使用
GsonHttpMessageConverter
, swagger v2 生成错误的json:{
"value": "{\"swagger\":\"2.0\",\"info\":{\"description\":\"Api Documentation\",\"version\":\"1.0\",\"title\":\"Api Documentation\",\"termsOfService\":\"urn:tos\",\"contact\":{\"name\":\"Contact Email\"},\"license\":{\"name\":\"Apache 2.0\",\"url\":\"http:
...
JSON 以 value 为前缀,真正的 JSON 成为转义字符串。
如果不使用
GsonHttpMessageConverter
应该是这样的:{
"swagger": "2.0",
"info": {
"description": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a
...
是否有解决方案可以创建正确的 swagger JSON 没有值和转义?
最佳答案
我自己解决了这个问题:
问题在于序列化此类:
package springfox.documentation.spring.web.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
@JsonRawValue
public String value() {
return value;
}
}
为了正确地序列化它,我实现了一个 SpringfoxJsonToGsonAdapter 并将其添加到我的 gson 配置中:
适配器:
public class SpringfoxJsonToGsonAdapter implements JsonSerializer<Json> {
@Override
public JsonElement serialize(Json json, Type type, JsonSerializationContext context) {
final JsonParser parser = new JsonParser();
return parser.parse(json.value());
}
}
gson配置:
@Configuration
public class GsonHttpMessageConverterConfig {
@Bean
public GsonHttpMessageConverter gsonHttpMessageConverter() {
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
converter.setGson(gson());
return converter;
}
private Gson gson() {
final GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Json.class, new SpringfoxJsonToGsonAdapter());
return builder.create();
}
}
关于spring-boot - springfox(swagger2) 不适用于 GsonHttpMessageConverterConfig,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30219946/