使用SwiftyJSON在Swift中解析JSON时遇到问题 [英] Trouble parsing JSON with Swift using SwiftyJSON
问题描述
我是新手,我正在尝试解析一些我从私有API中检索的简单JSON数据.我正在使用SwiftJSON库.
无论我做什么,我都无法为JSON响应中的变量"videoUploadId"分配"video_upload_id"的值.我希望我提供了足够的信息以获取帮助.谢谢
这是代码的一部分
let task = session.dataTaskWithRequest(request, completionHandler: { (data : NSData!, response, error : NSError!) -> Void in
if (error == nil) {
// Success
let statusCode = (response as NSHTTPURLResponse).statusCode
println("Status Code: \(statusCode)\r\n")
println("Response: \(response)\r\n")
println("Data: \(data)\r\n")
let dataContent = NSString(data: data!, encoding: NSUTF8StringEncoding)!
println("UTF8 Data: \(dataContent)\r\n")
let json = JSON(dataContent)
if let videoUploadId = json["video_upload_id"].int {
println("Video Upload ID (Dict: int): \(videoUploadId)")
}
else if let videoUploadId = json["video_upload_id"].string {
println("Video Upload ID (Dict: string): \(videoUploadId)")
}
else if let videoUploadId = json[0].int {
println("Video Upload ID (Array: int): \(videoUploadId)")
}
else if let videoUploadId = json[0].string {
println("Video Upload ID (Array: string): \(videoUploadId)")
}
else {
println(json["video_upload_id"].error)
}
}
else {
// Failure
println("URL Session Task Failed: %@", error.localizedDescription);
}
})
task.resume()
这是我从控制台收到的信息:
登录响应:HTTP 200 状态码:201
响应:{URL:https:////videos/uploads/} {状态代码:201,标头{ 连接=保持活动状态"; 内容长度" = 24; "Content-Type" =应用程序/json"; 日期="2015年1月25日星期日,格林尼治标准时间"; 位置="https:////videos/uploads/"; 服务器="Apache/2.2.15(CentOS)"; 的Set-Cookie"= 会话= eyJzZXNzaW9uX3Rva2VuIjp7IiBiIjoiUzAxWGFYRnlVVGM1YjBsa1kxWkJiV2xrYVZwcFZXdDFiR0ZLYW5GQ1VqRjFjbk5GIn19.B6XSMg.HXatQ76ZFaoZEQsnNu1BgsVECKA;仅Http;路径=/"; }
数据:< 7b227669 64656f5f 75706c6f 61645f69 64223a20 3736307d>
UTF8数据:{"video_upload_id":760}
可选(错误域= SwiftyJSONErrorDomain代码= 901"Dictionary [" video_upload_id]失败,它不是字典" UserInfo = 0x170238620 {NSLocalizedDescription = Dictionary ["video_upload_id"]失败,它不是字典})>
从代码和控制台输出中可以看到,我试图以几种不同的方式设置变量,所有这些似乎都失败了.我收到错误"Dictionary ["video_upload_id"]失败,这不是字典,我什至尝试在前缀"["和前缀]"之前尝试查看其格式问题.
有任何线索吗?
您执行的初始化错误.您应该使用:
let json = JSON(data:data) // data is NSData!
没有必要将NSData转换为NSString,这在某种程度上是错误的. SwiftyJSON只能使用NSData或Swift对象初始化.
I am new to swift and I am trying to parse some simple JSON data I am retrieving from a private API that I have. I am using the SwiftJSON library.
No matter what I do I cannot assign the variable "videoUploadId" with the value of "video_upload_id" coming from the JSON response. I hope i provided enough info to get some help. Thanks
Here is a segment of the code
let task = session.dataTaskWithRequest(request, completionHandler: { (data : NSData!, response, error : NSError!) -> Void in
if (error == nil) {
// Success
let statusCode = (response as NSHTTPURLResponse).statusCode
println("Status Code: \(statusCode)\r\n")
println("Response: \(response)\r\n")
println("Data: \(data)\r\n")
let dataContent = NSString(data: data!, encoding: NSUTF8StringEncoding)!
println("UTF8 Data: \(dataContent)\r\n")
let json = JSON(dataContent)
if let videoUploadId = json["video_upload_id"].int {
println("Video Upload ID (Dict: int): \(videoUploadId)")
}
else if let videoUploadId = json["video_upload_id"].string {
println("Video Upload ID (Dict: string): \(videoUploadId)")
}
else if let videoUploadId = json[0].int {
println("Video Upload ID (Array: int): \(videoUploadId)")
}
else if let videoUploadId = json[0].string {
println("Video Upload ID (Array: string): \(videoUploadId)")
}
else {
println(json["video_upload_id"].error)
}
}
else {
// Failure
println("URL Session Task Failed: %@", error.localizedDescription);
}
})
task.resume()
This is what I am receiving from my console:
Login Response: HTTP 200 Status Code: 201
Response: { URL: https:////videos/uploads/ } { status code: 201, headers { Connection = "Keep-alive"; "Content-Length" = 24; "Content-Type" = "application/json"; Date = "Sun, 25 Jan 2015 01:02:42 GMT"; Location = "https:////videos/uploads/"; Server = "Apache/2.2.15 (CentOS)"; "Set-Cookie" = "session=eyJzZXNzaW9uX3Rva2VuIjp7IiBiIjoiUzAxWGFYRnlVVGM1YjBsa1kxWkJiV2xrYVZwcFZXdDFiR0ZLYW5GQ1VqRjFjbk5GIn19.B6XSMg.HXatQ76ZFaoZEQsnNu1BgsVECKA; HttpOnly; Path=/"; } }
Data: <7b227669 64656f5f 75706c6f 61645f69 64223a20 3736307d>
UTF8 Data: {"video_upload_id": 760}
Optional(Error Domain=SwiftyJSONErrorDomain Code=901 "Dictionary["video_upload_id"] failure, It is not an dictionary" UserInfo=0x170238620 {NSLocalizedDescription=Dictionary["video_upload_id"] failure, It is not an dictionary})
As you can see from the code and console output, I am attempting to set the variable in several different ways all of which seem to fail. I am receiving the error "Dictionary["video_upload_id"] failure, It is not an dictionary" I even tried prepending "[" and appending "]" to try to see if its a formatting issue.
Any clues?
You are doing the initialization wrong. You should use:
let json = JSON(data:data) // data is NSData!
Converting NSData to NSString is not necessary, and somehow wrong for this. SwiftyJSON can only be initialized with NSData or Swift object.
这篇关于使用SwiftyJSON在Swift中解析JSON时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!