從api獲取數據的同時,我可以得到響應例如產品數組或產生錯誤的字典。如何在swift中解析未知的json數據類型2
如果一切合適的API發送的產品陣列:
[ "Product1": { name = "someting", price = 100, discount = 10%, images = [image1,image2] }, "Product2": { name = "someting", price = 100, discount = 10%, images = [image1,image2] } ]
但是,如果某些錯誤發生它發送字典中的錯誤信息和代碼:
{ error_message = "message" error_code = 202 }
我正在使用此代碼將JSON數據轉換爲數組:
do {
let jsonDict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray{
//Some code....
} catch let error as NSError {
print("JSON Error: \(error.localizedDescription)")
}
但如果我得到錯誤字典它崩潰。
問題: 1.如何知道接收到的數據是數組還是字典? 2.一些時間甚至鍵或值可以缺少這樣檢查的價值就變得非常冗長的代碼,如:
if let productsArray = jsonObject as? NSArray{
if let product1 = productsArray[0] as? NSDictionary{
if let imagesArray = product1["image"] as? NSArray{
if let imageUrl = imagesArray[0] as? String{
//Code ....
}
}
}
}
我讀到後衛關鍵字降低,如果條件,但我沒有明確的想法如何在這裏使用。
過得好的JSON? - 你能看到http響應狀態碼嗎? –
@thefredelement是的,我可以得到響應錯誤代碼,它是由我的服務器發送的特定於任何產品的請求,例如試圖獲取不可用的產品詳細信息。 –
我會推薦從Github上下載SwiftyJSON庫,所以你不需要有10個嵌套層次的if-let's –