- Xcode 9.0+Beta
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.
This sample defines a simple data type,
Grocery, and demonstrates how to construct instances of that type from several different JSON formats.
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:
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
Custom mappings let you to apply the Swift API Design Guidelines to the names of properties in your Swift model, even if the names of the JSON keys are different.
Access Nested Data
Learn how to ignore structure and data in JSON that you don’t need in your code. This playground uses an intermediate type to see how to extract grocery products from JSON that looks like this to skip over unwanted data and structure:
Merge Data at Different Depths
Combine or separate data from different depths of a JSON structure by writing custom implementations of protocol requirements from
Decodable. This playground shows how to construct a
Grocery instance from JSON that looks like this: