您的位置:首页 > 编程语言 > Java开发

解决Spring boot中使用Gson,Swagger2 api-docs无法正常显示json问题

2017-03-09 20:07 1271 查看
由于项目中存在自定义类型,而
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 也正常显示。

问题解决。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  gson spring
相关文章推荐