版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36666651/article/details/81200482
springboot中使用Gson作为序列化的实现后,访问swagger出现No operations defined in spec!
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Gson gson = new GsonBuilder()
.enableComplexMapKeySerialization()
.serializeNulls()
.setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")
.create();
converters.add(new GsonHttpMessageConverter(gson));
super.configureMessageConverters(converters);
}
然后访问swagger的ui界面时,出现了No operations defined in spec!提示。
原因是因为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;
}
}
在使用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());
}
}
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Gson gson = new GsonBuilder()
.enableComplexMapKeySerialization()
.serializeNulls()
.setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")
.registerTypeAdapter(Json.class, new SpringfoxJsonToGsonAdapter())
.create();
converters.add(new GsonHttpMessageConverter(gson));
super.configureMessageConverters(converters);
}
这样swagger就能正常使用了。