Using JSON in iOS Apps
JavaScript Object Notation (JSON) is a lightweight data-representation format that's easy for humans to read and interpret, and very efficient for computers to manipulate and generate. Based on a subset of the JavaScript programming language, JSON is a first-class citizen when dealing with JavaScript applications. Thanks to JSON's simplicity, almost all programming languages provide inherent support for it—including the Swift programming language used in iOS development.
In this article, I'll show you how to generate and manipulate JSON strings in your iOS applications.
JSON Structure
A JSON string consists of the following:
- A collection of key/value pairs. This is commonly represented in programming languages using dictionaries.
- An ordered collection of values. This is commonly represented in programming languages using arrays.
Because almost all programming languages support arrays and dictionaries, JSON has gained wide acceptance, and it's one of the most supported data formats for information interchange.
Let's examine a few JSON strings to see how they're formed.
JSON Example 1
Consider the following example:
{ "item1": "Apple", "item2": "Orange", "item3": "Pineapple" }
This very simple JSON string contains three key/value pairs. Notice that the JSON string is enclosed within a pair of braces ({}).
JSON Example 2
The following example shows another valid JSON string containing an array of three items:
[ "Apple", "Orange", "Pineapple" ]
In this case, the JSON string is enclosed with a pair of brackets ([]). Arrays in JSON are always enclosed using brackets.
JSON Example 3
The following example shows a JSON string containing a mixture of key/value pairs as well as arrays:
{ "basket1": [ "Apple", "Durian" ], "basket2": [ "Orange", "Peach" ], "basket3": [ "Pineapple", "Guava" ] }
Here, the value of each key (“basket1”, “basket2”, and “basket3”) is an array of strings.
JSON Example 4
The following more complicated example of a JSON string contains mixtures of key/value pairs as well as arrays:
{ "basket1": { "name": "Basket 1", "content": [ "Apple", "Durian" ] }, "basket2": { "name": "Basket 2", "content": [ "Orange", "Peach" ] }, "basket3": { "name": "Basket 3", "content": [ "Pineapple", "Guava" ] } }
Here, the value of each key (“basket1”, “basket2”, and “basket3”) is another dictionary; with the value of the second element (“content”) in the dictionary being an array.