Encode and decode JSON data, regardless of its structure, using Swift’s JSON support.

Overview

JSON data you send or receive from other apps, services, and files can come in many different shapes and structures. Use the techniques described in this sample to handle the differences between external JSON data and your app’s model types.

https://docs-assets.developer.apple.com/published/d7a01449d3/rendered2x-1581360204.png

This sample defines a simple data type, GroceryProduct, and demonstrates how to construct instances of that type from several different JSON formats.

struct GroceryProduct: Codable {
    var name: String
    var points: Int
    var description: String?
}

Read Data from Arrays

Use Swift’s expressive type system to avoid manually looping over collections of identically structured objects. This playground uses array types as values to see how to work with JSON that’s structured like this:

[
    {
        "name": "Banana",
        "points": 200,
        "description": "A banana grown in Ecuador."
    }
]

Change Key Names

Learn how to map data from JSON keys into properties on your custom types, regardless of their names. For example, this playground shows how to map the "product_name" key in the JSON below to the name property on GroceryProduct: