ios - How to parse JSON data properly if some data is NSNull -
i'm pulling data via twitter's search api.
once receive data, trying parse , save data tweetdetails class (which hold author's name, url of profile pic, text of tweet, location of tweet, tweet id , user id).
in cases, tweets not have location (i think has if they're retweeted), , dictionary (here being tweetsdict["place"]) otherwise hold information, instead returns nsnull.
on occasions, receive error
could not cast value of type 'nsnull' (0x1093a1600) 'nsdictionary' (0x1093a0fe8).
here code trying parse data , save objects in tweetdetails class
client.sendtwitterrequest(request) { (response, data, connectionerror) -> void in if connectionerror != nil { print("error: \(connectionerror)") } { let json = try nsjsonserialization.jsonobjectwithdata(data!, options: []) if let tweets = json["statuses"] as? [nsdictionary] { tweetsdict in tweets { let text = tweetsdict["text"] as! string let tweetid = tweetsdict["id_str"] as! string let place = tweetsdict["place"] as! nsdictionary // line ^^ error occurs let city = place.valueforkey("full_name") let user = tweetsdict["user"] as! nsdictionary let userid = user.valueforkey("id_str") let screenname = user.valueforkey("screen_name")! let avatarimage = user.valueforkey("profile_image_url_https")! let tweet = tweetdetails(authors: screenname as! string, profileimages: avatarimage as! string, tweettexts: text, tweetlocations: city as! string , tweetids: tweetid , userids: userid as! string) self.alltweets.append(tweet) self.tweettableview.reloaddata() } } } catch let jsonerror nserror { print("json error: \(jsonerror.localizeddescription)") } }
i have tried create 'if-let' statements provide alternatives these occasions, nothing has worked.
could please me create custom alternative around when json data returns nsnull. (even simple turning "city" variable string "unknown location" in cases when data returns nsnull).
thanks in advance , please let me know if there else can add provide more clarity question.
as others have pointed out, can use optional binding (if let
), or, in case, easier, employ optional chaining:
let city = tweetsdict["place"]?["full_name"] as? string
this way, city
optional, i.e. if no value found because there no place
or full_name
entry, nil
.
it appear, though, tweetdetails
force casting city
string
. absolutely require city? best change method city
optional , gracefully handle nil
values there. alternatively, can replace nil
values city
other string, e.g. nil
coalescing operator:
let city = tweetsdict["place"]?["full_name"] as? string ?? "unknown city"
that returns city if found, , "unknown city" if not.
Comments
Post a Comment