gpt4 book ai didi

Swift 2.0 和 3.0 中的 Json 解析

转载 作者:行者123 更新时间:2023-11-30 11:47:19 27 4
gpt4 key购买 nike

我们在 swift 解析 JSON 时遇到问题。如果您查看示例图像,您就会看到我们的问题。我们从 json 中获取字符串。当我们分配给dictionary2时,我们得到异常:

"Could not cast value of type '__NSArrayM' (0x10652de00) to 'NSDictionary' (0x10652e2d8)."

我们如何解析这个?我们无法将 swift 更新到最新版本。

let urlJsonToken2 = "https://jsonservices.mywebsite.com/api/en/News"
let myURL2 = NSURL(string: urlJsonToken2)
let request2 = NSMutableURLRequest(url: myURL2 as! URL)
request2.httpMethod = "GET"
request2.addValue("Bearer "+token!, forHTTPHeaderField: "Authorization")
request2.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
request2.setValue("application/json", forHTTPHeaderField: "Accept")
let task2 = URLSession.shared.dataTask(with: request2 as URLRequest) {(data2, response2, error2) -> Void in
if let unwrappedData2 = data2 {
do {
let requestReply = NSString(data: data2!, encoding: String.Encoding.ascii.rawValue)
let tokenDictionary2:NSDictionary = try JSONSerialization.jsonObject(with: unwrappedData2, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let Name = tokenDictionary2["Name"] as? String
}
catch {}
}
}
task2.resume()

Example

最佳答案

该错误告诉您您正在尝试将数组解析为字典。

let task2 = URLSession.shared.dataTask(with: request2 as URLRequest) {(data2, response2, error2) -> Void in
if let unwrappedData2 = data2 {
do {
guard let records = try? JSONSerialization.jsonObject(with: unwrappedData2, options: .mutableContainers) as? [[String: Any]] else {
print("[DEBUG] - Unable to parse JSON as array")
return
}

let firstRecord = records.first
print(records.count, firstRecord)

} catch {}
}
}

注意:使用 Swift 时,除非确实必要,否则应避免使用 NS 类。 Swift 有它自己的桥接类型。 NSDictionary = 字典,NSArray = 数组

关于Swift 2.0 和 3.0 中的 Json 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48680876/

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