Parsing and Using JSON in Swift
JSON, JavaScript Object Notation is a common language for API’s and web services to communicate with one and other. Think of it as a universal language that all programs can use to exchange information. It’s easy to use and is supported by all programming languages, so it is hugely popular.
A JSON response might look like the following:
[ { "animal": { "type": "Cat", "legs": "4" } }, { "animal": { "type": "Spider", "legs": "8" } } ]
This JSON response has 2 Animal Objects, each with a key value pair for the type of animal it is and how many legs it has.
Parsing JSON Natively in Swift
To parse this in native swift we would need to do the following:
// Store the JSON string let animals = "[{\"animal\":{\"type\":\"Cat\",\"legs\":\"2\"}},{\"animal\":{\"type\":\"Spider\",\"legs\":\"8\"}}]" // Convert the animals string to a JSON object. Typically you would get this in a response from a web server and start at this step. let animalsJSON = animals.data(using: .utf8)! // Try and parse the JSON if let parsedData = try? JSONSerialization.jsonObject(with: animalsJSON) as! [AnyObject] { // If we are able to parse it get the first object let firstObject = parsedData[0]["animal"] as! [String:Any] // Get the legs & type of animal for the first object let legs = firstObject["legs"] let type = firstObject["type"] // Print it out print(legs!) print(type!) }
This will output the number of legs and the type of the first animal in our JSON array which is a Cat with 4 legs. This is quite messy just to get these two values, imagine if you had an even larger JSON object, surely there is an easier way? Well lucky for us there is with Swifty JSON.
Parsing JSON with Swifty JSON
Swifty JSON is a CocoaPods libary to make using JSON in Swift a delight. In our XCode project create a podfile with pod init, then change it to the following. Noting that JSONParsing is our XCode Project Name.
platform :ios, '8.0' use_frameworks! target 'JSONParsing' do pod 'SwiftyJSON' end
Once installed with pod install, open the .xcworkspace and change the JSON parsing code to be the following:
// Store the JSON string let animals = "[{\"animal\":{\"type\":\"Cat\",\"legs\":\"4\"}},{\"animal\":{\"type\":\"Spider\",\"legs\":\"8\"}}]" // Convert the animals string to a JSON object. Typically you would get this in a response from a web server and start at this step. if let dataFromString = animals.data(using: .utf8, allowLossyConversion: false) { let animalsJSON = JSON(data: dataFromString) // Get the Animal Legs & Type let firstAnimalLegs = animalsJSON[0]["animal"]["legs"] let firstAnimalType = animalsJSON[0]["animal"]["type"] // Print out the Animal Legs & Type print(firstAnimalType) print(firstAnimalLegs) }
By using SwiftyJSON we can go straight to the animal legs and type. When dealing with much larger JSON objects you will find it much easier to use a library such as this to parse JSON.
Parsing JSON from an API End Point
So far we have been parsing JSON from a string, how about from a web server? Well that is simple. In this example we are using the Weather API for London, the JSON response we will be using using can be found at:
http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1
We are going to extract the type of weather (Sunny, Drizzly, Cloud) and the temperature. To get this we simply use the below with SwifyJSON:
// From an API let url = URL(string: "http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1") // Load the URL URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in // If there are any errors don't try to prase it guard let data = data, error == nil else { return } // Get the JSON from the URL let json = JSON(data: data) // Get the weather type and temprature let type = json["weather"][0]["main"] let temp = json["main"]["temp"] print(type) print(temp) }).resume()
This will result in the following output:
Drizzle 280.32
Easy right? JSON isn’t a scary monster that is confusing to use, its actually quite simple and easy. Armed with this you can now integrate your app with a vast number of API’s from the Weather, to Google Maps.