How to parse JSON using JSONSerialization. The ultimate guide.

Sometimes you need to parse JSON data by hand rather than using Codable. It could be helpful when you have to deal with generic data models. In these cases, you can use JSONSerialization.

How to parse JSON using JSONSerialization

  1. Fetch JSON data or load it from the local file.
  2. Feed the data to the JSONSerialization to create a parsed JSON object.
  3. Go through the created dictionary/array.

Let's take a closer look at each step.

Let's say we have the following JSON structure:

{
"users": [
	{"id": 234, "email": "bob@mycompany.com", "name": "Bob"},
	{"id": 235, "email": "jennifer@mycompany.com", "name": "Jennifer"},
	]
}

We can convert it into the Swift Data as follows:

let string = ""
let jsonData = string.data(using: .utf8)

 The next step is to parse the jsonData using JSONSerialization:

do {
	// Try to convert the data into a JSON object
    if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
        // try to find the "users" array
        if let users = json["users"] as? [User] {
            print(users)
        }
    }
} catch {
	print(error)
}

This is it. We have parsed the JSON string using JSONSeriaization and extracted the user's array from it.

JSON Editor for Mac

Clean, uncluttered, user-friendly. A must-have editor for JSON files.

Download Now