美文网首页Vapor
Vapor系列教程 - JSON

Vapor系列教程 - JSON

作者: CaryZheng | 来源:发表于2016-08-30 18:14 被阅读234次

Vapor 支持 JSON 类型,可直接使用。

JSON -> String


let json = try JSON(node: [
        "null": nil,
        "bool": false,
        "string": "Hello World",
        "int": 18,
        "double": 3.14,
        "object": JSON([
            "nested": "text"
            ]),
        "array": JSON(node: [nil, true, 123, "yes"])
        ])
    
let serialized = try json.makeBytes().string

print("\(serialized)")

输出

{"double":3.14,"object":{"nested":"text"},"int":18,"string":"Hello World","null":null,"bool":false,"array":[null,true,123,"yes"]}

String -> JSON


let serialized = "{\"name\":\"zzbTest\"}"
let json = try JSON(bytes: serialized.bytes)

print("\(json)")

输出

object(["name": JSON.JSON.string("zzbTest")])

Request


如果 Request Body 中包含 JSON 数据,可直接通过 Request 获取 JSON 数据。

假设 Body 数据为

{
    "name": "zzbTest",
    "pwd": "123456"
}

访问

let name = request.data["name"].string
let pwd = request.data["pwd"].string

print("name = \(name)")
print("pwd = \(pwd)")

输出

name = Optional("zzbTest")
pwd = Optional("123456")

Response


如果 Response 返回的格式是 JSON 格式,可直接返回 JSON 对象。

drop.get("json") { request in
    return try JSON([
        "name": "zzbTest"
    ])
}

访问 http://localhost:8080/json 将显示

{"name":"zzbTest"}

注意: 具体访问地址以实际配置为主)


Go to Vapor系列教程 - 目录

相关文章

  • Vapor系列教程 - JSON

    Vapor 支持 JSON 类型,可直接使用。 JSON -> String 输出 {"double":3.14,...

  • Vapor学习

    通过将Vapor官方文档进行梳理,了解Vapor所涉及到的知识点 Vapor英文教程Vapor中文教程官方Github

  • Vapor文档学习三 :JSON

    JSON在 Vapor里是不可或缺的,包括Vapor的配置都是采用json的格式,数据请求和数据应答中json也是...

  • Vapor系列教程 - 目录

    Vapor Version: v0.16 介绍 第一章 Vapor 起航1.1 macOS 安装 Swift1.2...

  • Vapor系列教程 - 介绍

    Vapor 是基于 Swift 实现的 Web 框架与服务,可运行于 macOS 和 Ubuntu 系统上。 特性...

  • Vapor系列教程 - Views

    Vapor 可直接返回纯 HTML 页面,也可以用 Mustache 或 Stencil 模版来渲染页面。 目录 ...

  • Vapor系列教程 - Middleware

    Middleware 是现代 Web 框架中必不可少的一部分。通过 Middleware 可以单独处理 Reque...

  • Vapor系列教程 - Validation

    Vapor 提供了一种机制来验证数据的合法性。 基本用法 验证 Employee 的 email 和 name 数...

  • Vapor系列教程 - Provider

    Provider 使得给 Vapor 添加功能和第三方 Package 变得更容易,只要遵循 Provider 协...

  • Vapor系列教程 - Droplet

    Droplet 是一个比较综合的类,它负责路由的注册、服务的启动和中间件的添加等等。 初始化 编辑 main.sw...

网友评论

    本文标题:Vapor系列教程 - JSON

    本文链接:https://www.haomeiwen.com/subject/ejxqettx.html