Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

ios

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()
                        }
like image 849
Amira Elsayed Ismail Avatar asked Mar 27 '16 23:03

Amira Elsayed Ismail


1 Answers

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.

like image 95
Alfie Hanssen Avatar answered Nov 14 '22 13:11

Alfie Hanssen