[英]Swift 2 parse Json as Optional to array
我從網絡服務獲取國家/地區列表。 收到后我用這個代碼來處理它:
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
為AnyObject
。 使用當前代碼,您將JSON數據轉換as? NSDictionary
as? NSDictionary
還是as? AnyObject
as? AnyObject
。
但由於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,但這取決於您。
試試這個
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.