# Decoding JSON in Swift the Easy Way with JSONSerialization

Fetching and using JSON data from APIs is a cornerstone of iOS development. Luckily, Swift provides an easy way to convert JSON into native data structures using `JSONSerialization`. Learn how in this quick tutorial.

## What is `JSONSerialization` in Swift?

`JSONSerialization` is a built-in class in Foundation that converts JSON data into instances of Swift data types like Dictionaries, Arrays, Strings, Numbers, booleans, and null.

It handles the heavy lifting of parsing the raw JSON text and making it usable in your code. `JSONSerialization` ensures proper conversion of types - converting JSON numbers to NSNumber instances, JSON arrays to Swift arrays, etc.

## Decoding JSON with `JSONSerialization`

Let's look at a simple example of fetching and decoding JSON from a network API call:

```swift
// Make API call and get Data 
let jsonUrl = "https://example.com/items.json"
guard let jsonData = try? Data(contentsOf: jsonURL) else {
  fatalError("Error fetching JSON data")
}

// Convert JSON Data to Swift Dictionary  
guard let jsonDict = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] else {
  fatalError("Error converting JSON data to Dictionary") 
}

// Access dictionary to get values
guard let title = jsonDict["title"] as? String else { return } 
guard let id = jsonDict["id"] as? Int else { return }
```

We make a network request to get the JSON data, then pass the Data to JSONSerialization's jsonObject method. This converts it to a Dictionary with String keys and Any values. We can then access the dictionary and unwrap values into proper Swift types like String and Int. I've simplified the guard statements for exposition purposes.

This provides easy and efficient JSON decoding, avoiding manual parsing. `JSONSerialization` handles ensuring proper type conversions.

For decoding arrays, jsonObject would return \[\[String:Any\]\] instead of \[String:Any\]. Nested JSON properties become nested Swift dictionaries and arrays.

## Custom Decoding with Codable

For more complex JSON structures, Swift's `Codable` protocol enables custom decoding beyond `JSONSerialization`. But for simple use cases, `JSONSerialization` provides an easy way to get started with JSON.

## Wrap Up

In summary, `JSONSerialization` is a powerful tool for accessing web APIs and converting JSON into usable Swift data. With just a few lines of code, you can easily decode JSON into native datatypes ready for your app.
