SwifyJSON – handling JSON format in Swift (the right way)

swiftyjson-swift

In this short tutorial, I will should you how to parse JSON format using the SwiftyJSON library.
Handling JSON with Swift can be pretty messy, so this library helps you doing the parsing in a more cleaner and easier way.

Let’s compare the native and SwiftyJSON approach.

 

The native approach:

if let statusesArray = try? NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [[String: AnyObject]],
    let user = statusesArray[0]["user"] as? [String: AnyObject],
    let username = user["name"] as? String {
    // Finally we got the username
}

 

The SwiftyJSON approach:

let json = JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string {
  //Now you got your value
}

 

As you can see the SwiftyJSON approach is more friendly than the native one. When you combine this library with Alamofire you are getting the perfect match for handling networking calls.

 

Leave a Reply

Your email address will not be published. Required fields are marked *