我需要将数组中的10个数组从JSON解析为swift并访问它。我可以通过REST API获取数据并在控制台上打印出来,但我不知道如何将其实际保存到进程中。
JSON数组结构:
[[lol_id, lol_time, lol_uid, lol_username, lol_type, lol_url, lol_title, lol_score, lol_comments, lol_badge],
[lol_id, lol_time, lol_uid, lol_username, lol_type, lol_url, lol_title, lol_score, lol_comments, lol_badge],
[lol_id, lol_time, lol_uid, lol_username, lol_type, lol_url, lol_title, lol_score, lol_comments, lol_badge],
[lol_id, lol_time, lol_uid, lol_username, lol_type, lol_url, lol_title, lol_score, lol_comments, lol_badge],
[lol_id, lol_time, lol_uid, lol_username, lol_type, lol_url, lol_title, lol_score, lol_comments, lol_badge],
[lol_id, lol_time, lol_uid, lol_username, lol_type, lol_url, lol_title, lol_score, lol_comments, lol_badge],
[lol_id, lol_time, lol_uid, lol_username, lol_type, lol_url, lol_title, lol_score, lol_comments, lol_badge],
[lol_id, lol_time, lol_uid, lol_username, lol_type, lol_url, lol_title, lol_score, lol_comments, lol_badge],
[lol_id, lol_time, lol_uid, lol_username, lol_type, lol_url, lol_title, lol_score, lol_comments, lol_badge],
[lol_id, lol_time, lol_uid, lol_username, lol_type, lol_url, lol_title, lol_score, lol_comments, lol_badge]]
这些数组基本上返回整数和字符串。
如何以相同的样式(数组中的数组)保存它们并访问它们?
这是我到目前为止的代码:
@IBAction func buttonLoad(sender: AnyObject) {
// Setting up the URL
let myUrl = NSURL(string: "http://hugelol.com/api/front.php");
// Request
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
println("error=\(error)")
return
}
// Prints server response
println("response = \(response)")
// Prints the double array
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")
}
task.resume()
}
我尝试了很多不同的方法,但在理解如何做到这一点时却遇到了很大的麻烦。我也尝试过swiftyJSON,但我仍然不知道如何将数据保存到swift数组中。我接近把头撞到墙上。谢谢你的阅读。
答案 0 :(得分:0)
尝试使用NSJSONSerialization。它将解析JSON并返回一个NSObject树。
if let result: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil) {...}
答案 1 :(得分:0)
这部分代码应该为您提供预期的结果
....
// Setting up the URL
let myUrl = NSURL(string: "http://hugelol.com/api/front.php");
// Request
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
println("error=\(error)")
return
}
if let jsonString = JSON(data: data).rawString() as String? {
if let dataFromString = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
// uncomment necessary access method
// for (index: String, subJson: JSON) in json {
// println("Arr = \(subJson)")
// }
// OR
// println(json[0][0])
}
}
}
task.resume()
...