Swift國(guó)內(nèi)社區(qū): SwiftMic
Vapor 支持 JSON 類(lèi)型,可直接使用。
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 數(shù)據(jù),可直接通過(guò) Request 獲取 JSON 數(shù)據(jù)。
假設(shè) Body 數(shù)據(jù)為
{
"name": "zzbTest",
"pwd": "123456"
}
訪問(wèn)
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 對(duì)象。
drop.get("json") { request in
return try JSON([
"name": "zzbTest"
])
}
訪問(wèn) http://localhost:8080/json 將顯示
{"name":"zzbTest"}
(注意: 具體訪問(wèn)地址以實(shí)際配置為主)
Go to Vapor系列教程 - 目錄