Json解析Swift 3 Alamofire
我是Swift 3的新手,在获取Json返回然后发送请求时遇到了问题。我正试图向服务器发送一个带有参数username和password的post请求,并获得一个带有信息的Json响应,但我无法获取返回的数据 输出: 错误:NSURLErrorDomain:-1003 状态代码:200,标题 连接=关闭; “内容类型”=“应用程序/json”; “传输编码”=标识 Android上的请求如下所示:Json解析Swift 3 Alamofire,json,swift,parsing,alamofire,Json,Swift,Parsing,Alamofire,我是Swift 3的新手,在获取Json返回然后发送请求时遇到了问题。我正试图向服务器发送一个带有参数username和password的post请求,并获得一个带有信息的Json响应,但我无法获取返回的数据 输出: 错误:NSURLErrorDomain:-1003 状态代码:200,标题 连接=关闭; “内容类型”=“应用程序/json”; “传输编码”=标识 Android上的请求如下所示: "{\n" + " \"jsonrpc\":
"{\n" +
" \"jsonrpc\": \"2.0\",\n" +
" \"id\": \"1\",\n" +
" \"method\": \"call\",\n" +
" \"params\": [\n" +
" \"" + LOGIN_TOKEN + "\",\n" +
" \"session\",\n" +
" \"login\",\n" +
" {\n" +
" \"username\": \"" + userName + "\",\n" +
" \"password\": \"" + password + "\"\n" +
" }\n" +
" ]\n" +
"}";
这是我应该发送的请求:
"{ \"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"call\", \"params\": [ \"00000000000000000000000000000000\", \"session\", \"login\", { \"username\": \"root\", \"password\": \"admin01\" } ] }"
这是我的代码:
override func viewDidLoad() {
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)
}
Alamofire.request("http://192.168.1.1/ubus", method: .post, parameters: jsonObject, encoding: JSONEncoding.default)
.responseJSON { response in
print(response)
//to get status code
if let status = response.response?.statusCode {
switch(status){
case 201:
print("example success")
default:
print("error with response status: \(status)")
}
}
//to get JSON return value
if let result = response.result.value {
let JSON = result as! NSDictionary
print(JSON)
}
}
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
您的JSON对象似乎无效 有一些非常有用的免费JSON验证程序。我想到的是 我认为,从您发布的代码中可以理解,您希望您的jsonObject看起来像这样,这是一个有效的JSON:
[
{
"jsonrpc": 2.0,
"id": 1,
"method": "call",
"params": ["00000000000000", "session", "login"],
"username": username,
"password": password
}
]
我假设
用户名
和密码
变量是您已经分配的字符串?尝试使用SwiftyJSON,我发现一些错误。“jsonrpc”后需要;而且任何类型都不能与数组一起使用,我在Android studio上收到了请求,它工作得很好。@GediminasUrbonas-这是因为它是JSON
code,而您正试图将它变成Swift
对象。您应该研究使用上述代码创建JSON
文件,然后学习如何将JSON
转换为Data
。您不能将JSON
代码转换为Swift数据
,它必须以某种方式进行转换。