Swift國內社區(qū): SwiftMic
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 數(shù)據(jù)夸赫,可直接通過 Request 獲取 JSON 數(shù)據(jù)。
假設 Body 數(shù)據(jù)為
{
"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系列教程 - 目錄