Many applications receive information from a server. It doesn't matter how the implementation of handling the data happens, there's a standard format that can be recognized by every client app.
Years ago, XML(1996) was widely used for this purpose. Since 2002 JSON has been the most popular format for transmitting data over the web.
- Identify JSON structures and create your own
- Read data from a file
- Encoding/Decoding a JSON file with JSONSerialization
- Encoding/Decoding a JSON file with the Codable protocol
JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format that allows us to read and write data that machines can also generate and parse easily.
Two main structures:
- Object: Collection of name/value pairs.
- Array: Ordered list of values.
An object begins with a left brace and ends with a right brace. Each name is followed by colon and the pairs are separated by commas.
An array begins with a left bracket and ends with a right bracket. Values are separated by commas.
Values can be strings in double quotes, numbers, true, false, null, objects or arrays. Also, structures can be nested.
A string is a sequence of 0 or more characters in double quotes.
Numbers are regular numbers like any language.
In the end, JSON is a way of communicating using very specific rules that every entity involved can agree on. 🌎
{
"festivals":[
{
"name":"Austin City Limits"
},
{
"name":"Riot Fest"
},
{
"name":"Coachella"
}
]
}
Without using a format validator, create your own JSON file to represent a list of festivals. Include two festival entries. They do not have to be real.
Consider you have these structs as reference:
struct Participant{
let name: String
let id: String
}
struct City{
let name: String
let id: String
}
enum FestivalType{
case music
case food
case cinema
}
struct Festival{
let date: Date
let name: String
let city: City
let lineup: [Participant]
let type: FestivalType
}
After you are done writing the structure use the JSON validator to make sure your format is correct. If not, do the necessary adjustments.
“Serializing a program’s internal data structures into some kind of data interchange format and vice versa is one of the most common programming tasks. Swift calls these operations encoding and decoding.”Excerpt From: Chris Eidhof. “Advanced Swift.”
Types conform to the Encodable and/or Decodable protocols to state their ability to encode themselves and to create an instance from data.
Most types will adapt both, so the standard library came up with a typealias for both: the Codable protocol.
public typealias Codable = Encodable & Decodable
Universality
Should work with structs, enums and classes.
Type safety
JSON is often weakly typed, but we're working with Swift so our code works with strongly typed data structures.
Reducing boilerplate
Writing less code, while the compiler generates what we need automatically.
When we have a value that conforms to the Codable protocol we can:
- Create an encoder to serialize the value into JSON. (JSONEncoder is built-in in Swift)
- Create a decoder that takes the serialized data and turns it into an instance of the original type. (JSONDecoder is built-in in Swift)
Error handling is important during decoding. Many things can go wrong (missing fields, type mismatches, corrupted data, etc.)
We can control how a type encodes itself by writing a custom CodingKeys enum.
- Rename fields by giving string values
- Skip fields by omitting keys
This time we created our structs from scratch to understand where everything comes from.
In the future, if you are given the JSON data to review it first, you can generate the struct file automatically with this tool:
It can definitely serve as a starting point in the future. 😉
Part 1: Follow this guide to practice how to parse JSON and use it in an Xcode project using JSONSerialization.
Part 2: Follow this guide to practice how to use the Codable protocol.
Q: How does the encoding process work?
Q: What does the compiler handle when using Codable?
Q: How does the decoding process work?
Q: What are coding keys? How are they useful?
- XML vs JSON
- JSON documentation
- JSON format validator
- Film locations
- Codable sheet
- (Book) “Advanced Swift.” by Chris Eidhof 1.Medium article