2015-02-05 64 views
2

我想用下面的代碼來解析JSON:鑄造AnyObject到雙

func ltchandler(response: NSURLResponse!, data : NSData!, error : NSError!) { //Is passed the results of a NSURLRequest 

    if ((error) != nil) { 
     //Error Handling Stuff 
    } else { 
     if (NSString(data:data, encoding:NSUTF8StringEncoding) == "") { 

      //Error Handling Stuff 
     } else { 
      var data = NSData(data: data); 

      // Define JSON string 
      var JSONString = "\(data)" 



      // Get NSData using string 
      if let JSONData = JSONString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { 


       // Parse JSONData into JSON object 
       var parsingError: NSError? 
       if let JSONObject = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &parsingError) as? [String: AnyObject] { 


        // If the parsing was successful grab the rate object 
        var rateObject: Double! = JSONObject["price"]?.doubleValue 

        // Make sure the rate object is the expected type 
        if let rate = rateObject as? Double! { // THIS IS NOT WORKING!!! 
        //Do stuff with data 
        } else { 
         println("Parsing Issue") 

        } 
       } 
      } 

     } 
    } 



} 

線條爲標誌THIS IS NOT WORKING!!!不會被調用。

從我可以告訴,它不能將rateObject作爲一個雙 - 爲什麼不?它沒有顯示任何錯誤。

爲了澄清,預期的行爲是從JSON對象創建一個double。

回答

6

要嚴格回答您的問題,您是否嘗試過打印rateObject。另外你爲什麼要在Double!而不是Double在問題行?

我個人幾乎在所有情況下都不使用!。你最好使用非可選項或適當的可選項。

在培訓相關部分,我會寫:

// Make sure the rate object is the expected type 
if let rate = JSONObject["price"]?.doubleValue { 
    //Do stuff with rate 
} else { 
    print("Parsing Issue") 
} 

當然如果JSONObject["price"]是不是有doubleValue方法或該方法返回nil你將結束零和其他情況下上當受騙。

+1

感謝羅布,答案改善。 – 2015-02-05 14:15:31

+0

謝謝,它工作 – MShah 2016-07-26 11:59:34

1

代碼爲我工作,試試這個代碼:

// if the value equals nil or any String, the instruction abort the if 
// SWIFT 2.0 in xcode beta 5 
if let rate = Double((JSONObject["price"] as? String)!){ 
    // insert you code here 
} else { 
    print("error message") 
}