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就能正常使用了。