Vapor文档学习三 :JSON

JSON在 Vapor里是不可或缺的,包括Vapor的配置都是采用json的格式,数据请求和数据应答中json也是更加简便的数据交互方式。

Request

JSON总是会和form-urlencoded dataquery data绑定在一起,并且在 request.data中自动获取,也就是你可以专注于API的开发,而不必担心content types的设置。

drop.get("hello") { request in
    guard let name = request.data["name"]?.string else {
        throw Abort.badRequest
    }
    return "Hello, \(name)!"
}

不管是以什么HTTP methodcontent type发送的name,最后都会返回成功。

JSON Only

如果只接收JSON数据,可以使用request.json

drop.post("json") { request in
    guard let name = request.json?["name"]?.string else {
        throw Abort.badRequest
    }

    return "Hello, \(name)!"
}

只有post的数据是json的格式,这个请求才会成功。

Response

对于respondjson数据,可以使用JSON(node: )进行格式化。

drop.get("version") { request in
    return try JSON(node: [
        "version": "1.0"
    ])
}

Middleware(数据交换格式)

JSONMiddlewareDroplet默认的middleware . 如果你不想用JSON语法解析,你可以删除。

你可能感兴趣的:(Vapor文档学习三 :JSON)