Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift. How can I deal with null values into json files?

Tags:

json

null

ios

swift

I'm reading json from a URL and, again (I had the same issue with ObjectiveC) the values crash my app. I don't have any problems with Strings and Numbers. I can println(value) but when I assign the value into a UILabel, it crashes.

I use this method to read the JSON:

func jsonFromURL(jsonURL: String) -> Dictionary<String, AnyObject> {
    var jsonNSURL: NSURL = NSURL(string: jsonURL)
    let jsonSource: NSData = NSData(contentsOfURL: jsonNSURL)
    var json = NSJSONSerialization.JSONObjectWithData(jsonSource, options:NSJSONReadingOptions.MutableContainers, error: nil) as Dictionary<String, AnyObject>
    return json
}

...and this code to assign values into a UILabel inside a custom Cell

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell? {

    var regularTextCell:celda = celda(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
    var cell:celda = NSBundle.mainBundle().loadNibNamed("celda", owner: self, options: nil)[0] as celda

    cell.name.text = myJson["list"]![indexPath.row]!["name"] as String
    cell.id.text = "id: " + String(myJson["list"]![indexPath.row]!["id"] as Int)

    // THIS line crash because some values of adress are <null>
    cell.address.text = myJson["list"]![indexPath.row]!["address"] as String

    return cell

}

You can view an example of the JSON at: https://dl.dropboxusercontent.com/u/787784/example.json

Thanks!

like image 626
Francis Vega Avatar asked Jun 09 '14 20:06

Francis Vega


People also ask

How do I allow null values in JSON?

To include null values in the JSON output of the FOR JSON clause, specify the INCLUDE_NULL_VALUES option. If you don't specify the INCLUDE_NULL_VALUES option, the JSON output doesn't include properties for values that are null in the query results.

Can JSON handle null values?

JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.

Can null be a JSON key?

JSON object keys must be strings according to the specification. Therefore null is not allowed as JSON object key. So the reason it fails is because what you are returning can not be serialized to a valid JSON structure.

How do you handle null in Codable Swift?

A null value (no string) is treated as nil by default so the decoding is supposed to succeed if the property is optional. By the way: You can omit the CodingKeys. If the name of the properties are the same as the keys you don't need explicit CodingsKeys .


2 Answers

You'll get an exception from syntax like object as String if object is not a String. You can avoid the exception by using object as? String which may result in a nil being assigned into your text.

In your specific case you could use:

cell.address.text = (myJson["list"]![indexPath.row]!["address"] as? String) ?? "default"

where I've replaced your as with as? and exploited the nil-coalescing operator ??.

like image 104
GoZoner Avatar answered Oct 17 '22 21:10

GoZoner


I found this solution in online Swift tutorial. It's very nice solution how to deal with null value in Swift.

This is the concept:

 let finalVariable = possiblyNilVariable ?? "Definitely Not Nil Variable"

In tutorial example :

  let thumbnailURL = result["artworkUrl60"] as? String ?? ""

Here is the link for tutorial: http://jamesonquave.com/blog/developing-ios-8-apps-using-swift-interaction-with-multiple-views/

like image 9
Marijan V. Avatar answered Oct 17 '22 22:10

Marijan V.