Could not cast value of type 'NSNull' to 'NSString' in parsing Json in swift

前端 未结 2 1145
一生所求
一生所求 2021-02-04 12:07

I have the following class

class BannerResponse : NSObject{

    let  URL                = \"Url\";
    let  CONTACT_NO         = \"ContactNo\";
    let  IMAGE          


        
2条回答
  •  [愿得一人]
    2021-02-04 12:42

    You are getting null values for some of your keys. They get mapped to NSNull by NSJSONSerialization.

    You need to do several things

    Change all your variables (url, contactNo, etc) to optionals:

    var url:String?
    var contactNo:String?
    

    Change all of your assignments to use ? instead of !:

    url = noNulls[URL] as? String
    contactNo = noNulls[CONTACT_NO] as? String
    

    And finally, make your code handle nil values for all of your variables. (But do not use !. That path leads to crashes.)

提交回复
热议问题