gpt4 book ai didi

ios - 快速解析双 JSON 编码数组并访问它

转载 作者:行者123 更新时间:2023-11-28 09:08:20 25 4
gpt4 key购买 nike

我需要将一个数组中的 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 数组中。我差点把头撞到墙上。感谢您阅读。

最佳答案

这部分代码应该提供给你预期的结果

....

// 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()

....

关于ios - 快速解析双 JSON 编码数组并访问它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30263874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com