2016-09-23 53 views
-2

我想從響應中解析JSON。但我得到這個錯誤
我的代碼是。無法將'__NSCFString'(0x104a67320)類型的值轉換爲'NSDictionary'(0x104a68108)

NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) in 

    if error != nil { 
     print("error = \(error)") 
     return 
    } 
    do { 
     let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding) 
     print("responseString = \(responseString)") 

     let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSDictionary 

     let str = json["ResultMsg"] as! NSString  
     print ("ResultMsg = " + (str as String)) 

    }catch let error as NSError { 
     print("Error : " + error.localizedDescription) 
    } 
}).resume() 

和控制檯日誌是:

responseString =可選( 「{\」 ResuleCode \ 「:\」 1 \ 「\ 」ResultMsg \「:\ 」SUCCESS \「,\」結果\ 「:[{\」 UserIdx \ 「:\」 4138 \ 「\ 」電子郵件\「:\ 」[email protected] \「,\ 」用戶名\「:\ 」測試1 \「,\」 PWD \ 「:\」 v + Mb90ZS + Y5Qt9DfuBcJtQ == \ 「\ 」電話\「:\ 」\「,\ 」的AppKey \「:\ 」\「,\ 」LoginDt \「:\」 9/23/2016 1:12:18 PM \「,\」LogoutDt \「:\」2016/9/1 10:36:02 \「,\」RegDt \「:\」2016/8/31 9:26: 「\」,\「KeywordTime \」:\「60 \」,\「KeywordEnabled \」:\「1 \」,\「FastEnabled \」:\「1 \ 」,\ 「KeywordStartTime \」:\ 「08:30:00 \」,\ 「KeywordEndTime \」:\ 「15:30:00 \」,\ 「FastStartTime \」:\ 「08:00:00 \」, \ 「FastEndTime \」:\ 「15:30:00 \」,\ 「IsFirst \」:\「NOT_FIR ST \」,\ 「IsFastNews \」:\ 「1 \」 \ 「IsKeywordNews \」:\ 「1 \」 \ 「KeywordStartDt \」:\ 「\」 \ 「KeywordEndDt \」:\ 「\」} ]}「)
無法將'__NSCFString'(0x10abdf320)類型的值轉換爲'NSDictionary'(0x10abe0108)。

任何幫助將不勝感激!

+0

放斷點,並檢查其行拋出這個錯誤? –

+0

讓json =試試NSJSONSerialization.JSONObjectWithData(data !, options:.AllowFragments)as! NSDictionary - >這一行是問題..信號SOGABRT –

+0

@MoonJikLee你可以顯示你的實際JSON響應,而不是顯示我們的Xcode響應。 –

回答

0

試試這個:

do{ 
    if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSDictionary 

    print("parse success") 
}catch{ 
    print("parse error") 
} 
+0

看看你是否得到解析錯誤或成功。 –

+0

「如果讓兒子= xxxxx」行有錯誤。 「條件綁定的初始化必須有可選類型,而不是'NSDoctionary'。 –

+0

'as?NSDictionary'或Better' as?[String:AnyObject]' –

0

試試這個代碼:

let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSMutableDictionary 
+0

同樣的錯誤發生。 –

-1

我發現這個代碼工作。

if let responseData = responseString!.dataUsingEncoding(NSUTF8StringEncoding) 
{ 
    let json = try NSJSONSerialization.JSONObjectWithData(responseData, options: .AllowFragments)     
    print(json) 
} 

但我不知道確切的原因..感謝所有反正

+0

這不是正確的方法來應對我的答案和給出答案 –

+0

首先你要求回答,然後你正在回答我的答案併發帖作爲答案,請你告訴我你的答案和我的答案有什麼區別? –

相關問題