gpt4 book ai didi

ios - Swift 2 将 Json 解析为数组的可选

转载 作者:搜寻专家 更新时间:2023-10-31 08:32:58 25 4
gpt4 key购买 nike

我正在从网络服务中获取国家列表。收到后我用这段代码来处理它:

if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
// triggering callback function that should be processed in the call
// doing logic
} else {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? AnyObject {
completion(json)
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON string: \(jsonStr)")
}
}

在该列表之后看起来像这样(它在这部分结束 NSJSONSerialization.JSONObjectWithData(data!, options:[]) as?AnyObject):

 Optional((
{
"country_code" = AF;
"dial_code" = 93;
id = 1;
name = Afghanistan;
},
{
"country_code" = DZ;
"dial_code" = 213;
id = 3;
name = Algeria;
},
{
"country_code" = AD;
"dial_code" = 376;
id = 4;
name = Andorra;
}
))

我现在应该将此 json 对象转换为数组(或以某种方式使用 NSDictionary)并循环遍历它。有人可以建议怎么做吗?

最佳答案

目前您不能遍历您的对象,因为它已被您的代码转换为 AnyObject。使用您当前的代码,您正在将 JSON 数据转换为 as? NSDictionary 还是 作为?任何对象

但由于 JSON 总是以字典或数组开头,因此您应该改为这样做(保留您的示例):

if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
// process "json" as a dictionary
} else if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? NSArray {
// process "json" as an array
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON string: \(jsonStr)")
}

理想情况下,您会使用 Swift 字典和数组而不是 Foundation 的 NSDictionary 和 NSArray,但这取决于您。

关于ios - Swift 2 将 Json 解析为数组的可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33509167/

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