【发布时间】:2017-05-24 02:47:46
【问题描述】:
我在使用 Swift 3 时遇到问题,我正在尝试向服务器发送请求并获取 JSON,但我得到了:
施工过于复杂,无法在合理的时间内解决。
各种方法都试过了,还是不行。
var userName = "root"
var password = "admin01"
//var LOGIN_TOKEN = 0000000000000000
let parameters = [
"{\n",
" \"jsonrpc\": \"2.0\",\n",
" \"id\": \"1\",\n",
" \"method\": \"call\",\n",
" \"params\": [\n",
" \"0000000000000000\",\n",
" \"session\",\n",
" \"login\",\n",
" {\n",
" \"username\": \"" + userName + "\",\n",
" \"password\": \"" + password + "\"\n",
" }\n",
" ]\n",
"}"
]
let joiner = ""
let joinedStrings = parameters.joined(separator: joiner)
print("joinedStrings: \(joinedStrings)")
// All three of these calls are equivalent
Alamofire.request("http://192.168.1.1", method: .post, parameters: parameters).responseJSON { response in
print("Request: \(response.request)")
print("Response: \(response.response)")
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
现在我尝试创建 dic 并转换为 Json,但在那之后,我在请求时遇到问题,我声明了我的参数。他们说:使用未解析的标识符dictFromJSON
var userName = "root"
var password = "admin01"
//var LOGIN_TOKEN = 0000000000000000
let jsonObject: [String: Any] =
["jsonrpc" : 2.0,
"id": 1,
"method": "call",
"params": [ "00000000000000",
"session",
"login",
[ "username": userName,
"password": password]],
]
do {
let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type `Any`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch {
print(error.localizedDescription)
}
// All three of these calls are equivalent
Alamofire.request("http://192.168.1.1/ubus", method: .post, parameters: dictFromJSON).responseJSON { response in
print("Request: \(response.request)")
print("Response: \(response.response)")
【问题讨论】:
-
无论如何都不要手动创建 JSON 字符串。创建数组和字典,然后将它们转换为 JSON。 stackoverflow.com/a/31263337/2227743
-
现在我得到错误:调用中的额外参数“方法”。你能帮我解决这个问题吗?
-
这只是一个恰好出现在 Swift 2 中的例子。重要的是想法。其他例子大家可以自己找,有很多。
-
我创建了 dic 并转换为 JSon,但我遇到了另一个问题,请检查我的问题,我已更新。