Parsing JSON to Dictionary in Swift from an API
EDIT 2020: I’ve now taken a back seat from Swift and have gone all in on React Native, Laravel & Vue — lukecurtis.me if you’re looking for more tech goodies
After searching countless hours on SO and Google for a succinct answer to this I’ve taken it upon myself to put together a beginners guide to parsing JSON response from an API to a Dictionary in Swift.
Before I continue, I am a complete novice when it comes to Swift. I dabble from time to time but this was more of an exercise to see how it easy it is to do what should be relatively easy in any programming language. I’ve done this in a swift playground for brevity.
Skip to the bottom for just the code
UPDATE: If you need to worry about headers, I’ve made a revised version here
Scenario:
Lets say you have the following JSON data returned from a URL and we want it to be in a dictionary of Colours.
[
{
"id": 1,
"name": "Blue"
},
{
"id": 2,
"name": "Red"
}
]
First things first, start a new playground. I’m not gonna get you to set up a new project for this one — a blank one is fine
Next up you’re gonna need to import all the necessary frameworks to run up some of the method we’re gonna be calling when parsing this data from a URL.
import Foundationimport XCPlaygroundimport PlaygroundSupportimport UIKit
IMPORTANT: If you’re using playgrounds here add the following to the bottom of the file
PlaygroundPage.current.needsIndefiniteExecution = true
Next up we’re gonna create the new struct
to store the results from our API call later on
struct Colour: Codable { let name: String let id: Int func getString() { print( "Name: \(name), Id: \(id)" ) }}
It’s pretty clear what’s happening here, we’re essentially creating our own structure with a method to display the colours once we’ve saved it. You could use a class for this, but once again we’re mainly here to get that API data properly.
Next up, just create a dictionary of colours from this struct, so:
var colours = [Int: Colour]()
Now for the reason you’re here, grabbing that JSON and parsing it
do { if let file = URL(string: "http://example.test/colours") { let data = try Data(contentsOf: file) let json = try JSONSerialization.jsonObject(with: data, options: []) } else { print("no file") }} catch { print(error.localizedDescription)}
Here, we’re grabbing the URL (in string format) and storing the result of that in a Data variable. It’s just a raw byte data type. We’re then serialising that to a JSON object with the JSONSerialization import.
Here comes the fun bit. We now have our JSON object as an array in swift so it’s pretty easy to loop through this and add it to our list of colours — add this directly under the line where you declare the json
variable
if let object = json as? [Any] { for anItem in object as! [Dictionary<String, AnyObject>] { let colourName = anItem["name"] as! String let colourID = anItem["id"] as! Int let colour = Colour(name: colourName, id: colourID) colours[colourName] = colour colours[colourID]?.getString() }} else {print("JSON is invalid")}
Here, we create the object variable and loop through the colours we just got from our API call and cast that to a temporary dictionary so we can then parse the results to the correct types (remember the id may have come as a string) and store it in the Dictionary with the like industries[industryID = industry
.
Easy as that!
There are many ways to do this sort of thing but for me this is what feels like the simplest and easiest for beginners. Remember, it doesn’t cover too many error checks so always watch out for that when working with your own API.
If you have any improvements or comments, please leave comment or tweet me @ilukecurtis