返回 JSON 数据 封面
Vapor 大型教程

返回 JSON 数据

现代接口大多返回 JSON。本文用 Vapor 的 Content 协议,让结构体自动编成 JSON,并通过一个 POST 路由把数据原样返回。

让结构体自动编码为 JSON

Content 协议也可以编码结构体成为 JSON 数据,在代码中定义一个遵循 Content 协议的结构体 InfoResponse,使用请求数据初始化一个响应结构体对象,直接返回,JSON 编码会自动完成,并返回 JSON 数据给用户。

import Vapor

func routes(_ app: Application) throws {
    app.get { req in
        return "It works!"
    }

    app.get("hello") { req -> String in
        return "Hello, world!"
    }

    // Add Routes
    app.get("hello", ":name") { req -> String in
        guard let name = req.parameters.get("name", as: String.self) else {
            return "\(HTTPStatus.notFound)"
        }
        return "Hello, \(name)"
    }
    // ---
    app.post("info") { (req) -> InfoResponse in
        let info = try req.content.decode(InfoData.self)

        let response = InfoResponse(requestData: info)
        return response
    }

}


struct InfoData: Content {
    let name: String
}

struct InfoResponse: Content {
    let requestData: InfoData
}

用 curl 测试

下面是测试命令:

curl http://localhost:8080/info \
-X POST \
-H "content-type:application/json" \
-d '{"name":"joker"}' 

返回的 JSON:

{"requestData":{"name":"joker"}}

用 jq 格式化输出

如果想格式化输入的话,可以使用 jq 工具命令。

  • jq 这个命令行工具,系统可能没有自带。
  • macOS 可以使用 brew install jq 进行安装。
  • Ubuntu 可以使用 sudo apt-get install jq -y 进行安装。
curl -s http://localhost:8080/info \
-X POST \
-H "content-type:application/json" \
-d '{"name":"joker"}' | jq
{
    "requestData": {
        "name": "joker"
    }
}

使用 rested 应用测试如下。


本系列其他文章