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

前端 未结 2 1144
一生所求
一生所求 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:28

    One of your data[SOME_KEY] is of type NSNull instead of String and because you're forcing the cast to String by using ! the app crashes.

    You can do one of two things:

    1. Change your variables on the BannerResponse class to be optional. And use ? instead of ! when setting the values in your init method. Like this:

    `

    var title: String?
    
    init(data: NSDictionary) 
    {
        self.title = data[TITLE] as? String
    }
    

    or

    1. Use ? instead of ! when setting the values in your init method but set a default value whenever dict[SOME_KEY] is nil or is not the expected type. This would look something like this:

    `

    if let title = data[TITLE] as? String 
    {
        self.title = title
    }
    else
    {
        self.title = "default title"
    }
    
    // Shorthand would be: 
    // self.title = data[TITLE] as? String ?? "default title"
    

    And I guess a third thing is ensure that the server never sends down null values. But this is impractical because there's no such thing as never. You should write your client-side code to assume every value in the JSON can be null or an unexpected type.

    0 讨论(0)
  • 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.)

    0 讨论(0)
提交回复
热议问题