由于项目中存在自定义类型,而Jackson
的序列化与反序列化又不太会玩,转而使用Gson
,由于有生成Restful API文档的需求,使用Swagger2,最终api-docs
无法正常显示(使用Jackson
一切正常):
{
"value": "{\"swagger\":\"2.0\",\"info\":{\"description\":\"this is restful api document\",\"version\":\"1.0.0\",\"title\":\"MyApp API文档\",\"contact\":{\"name\":\"xxx\",\"url\":\"http://xxxx.com\",\"email\":\"xxx@xxx.com\"}},\"host\":\"localhost:8080\",\"basePath\":\"/\",\"tags\":[{\"name\":\"login-controller\",\"description\":\"Login Controller\"},{\"name\":\"user-controller\",\"description\":\"User Controller\"}],\"paths\"
......
同时也导致/swagger-ui.html
无法正常显示。
原因:Gson
的序列化问题
解决方法:自定义Gson
序列化
//***注意***:这里的`Json`是`springfox.documentation.spring.web.json.Json`包下的类
class springfoxJsonToGsonAdapter : JsonSerializer<Json> {
override fun serialize(json: Json, type: Type, jsc: JsonSerializationContext): JsonElement
= JsonParser().parse(json.value())
}
接下来注册到GsonHttpMessageConverter
//***注意***:`Json`同上,为`springfox.documentation.spring.web.json.Json`包下的类
class IGsonHttpMessageConverter : GsonHttpMessageConverter() {
init {
//自定义Gson适配器
super.setGson(GsonBuilder()
.registerTypeAdapter(Json::class.java, springfoxJsonToGsonAdapter())
.create())
}
}
接下来访问http://localhost:8080/v2/api-docs
,得到正常结果
{
"swagger": "2.0",
"info": {
"description": "this is restful api document",
"version": "1.0.0",
"title": "MyApp API文档",
"contact": {
"name": "userName",
"url": "http://xxxuri.com",
"email": "mail@mailbox.com"
}
},
"host": "localhost:8080",
"basePath": "/",
"tags": [{
"name": "login-controller",
"description": "Login Controller"
}, {
"name": "user-controller",
"description": "User Controller"
}],
"paths": {
"/login/verify/{userId}": {
"get": {
"tags": [
"login-controller"
],
"summary": "askGroupsAndRoles",
"operationId": "askGroupsAndRolesUsingGET",
"consumes": [
"application/json"
],
"produces": [
"*/*"
],
"parameters": [{
"name": "userId",
"in": "path",
"description": "userId",
"required": true,
"type": "string" }],
"responses": {
"200": { "description": "OK" },
"401": { "description": "Unauthorized" },
"403": { "description": "Forbidden" },
"404": { "description": "Not Found" } }
}
}
}
Swagger UI 也正常显示。
问题解决。