Cannot pass value like "NSNull" to "NSString" when parsing Json in swift

I have the following class

class BannerResponse : NSObject{ let URL = "Url"; let CONTACT_NO = "ContactNo"; let IMAGE = "Image"; let BIG_IMAGE = "BigImage"; let ID = "Id"; let TITLE = "Title"; let NO_VIEW = "NoView"; let START_DATE = "StartDate"; let END_DATE = "EndDate"; var url:String; var contactNo:String; var image:String; var bigImage:String; var title:String; var id:Int; var noView:Int; var startDate:String; var endDate:String; init(data : NSDictionary){ url = data[URL] as! String; contactNo = data[CONTACT_NO] as! String; image = data[IMAGE] as! String; bigImage = data[BIG_IMAGE] as! String; title = data[TITLE] as! String; id = data[ID] as! Int; noView = data[NO_VIEW] as! Int; startDate = data[START_DATE] as! String; endDate = data[END_DATE] as! String; } } 

when i run the code i got the following error

 Could not cast value of type 'NSNull' (0x10a85f378) to 'NSString' (0x109eccb20). 

EDIT

 do { if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary{ onSuccess(BannerResponse(data: json)) } } catch { onFail() } 
+5
source share
2 answers

One of your data[SOME_KEY] is of type NSNull instead of String and because you force the cast to String with ! , the application crashes.

You can do one of two things:

  • Change the variables in the BannerResponse class as optional. And use ? instead ! when setting values ​​in your init method. Like this:

`

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

or

  1. Use ? instead ! when setting values ​​in your init method, but set the default value when dict[SOME_KEY] is zero or not the expected type. It will 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 think the third thing is to ensure that the server never sends empty values. But this is impractical because there is no such thing as never before. You should write your client-side code to suggest that each value in JSON may be null or unexpected.

+20
source

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

You need to do a few things

Change all variables ( url , contactNo , etc.) to options:

 var url:String? var contactNo:String? 

Change all your assignments to use ? instead ! :

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

Finally, make your code a nil descriptor for all of your variables. (But do not use ! This path leads to failures.)

-1
source

Source: https://habr.com/ru/post/1245879/


All Articles