You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: course/swift4/codable-json.md
+71-6
Original file line number
Diff line number
Diff line change
@@ -1,30 +1,55 @@
1
1
# Codable and JSON Serialization
2
2
## Introduction
3
+
Welcome, everyone. Today, you will learn how to convert an object to a json file vice versa with a single line of code. If you have never worked with `JSON` before, don't you worry. I will walk you through.
4
+
3
5
## Problem
4
-
Map JSON to Object in one line of code
6
+
Map JSON to Object in one line of code and the opposite
5
7
6
-
## Conclusion
8
+
9
+
### Introducing JSON
10
+
How to resemble a `json` file as seen in the previous lesson.
7
11
8
12
```swift
9
13
let republicOfKorea =JSON(dictionary: [
10
14
"capital":"Seoul",
11
15
"name":"Republic of Korea",
12
16
"population":50000000
13
17
])
18
+
```
19
+
20
+
The `json` format above would look,
21
+
22
+
```json
23
+
{
24
+
"capital": "Seoul",
25
+
"name:": "Repulibc of Korea",
26
+
"population": 50000000
27
+
}
28
+
```
29
+
30
+
When you make an API call, `https://itunes.apple.com/lookup?id=909253`you will receive data from the server,
14
31
15
-
let koreaCaital: String?= republicOfKorea["capital"]
16
-
let koreaName: String?= republicOfKorea["name"]
17
-
let koreaPopulation: Int?= republicOfKorea["population"]
let bob =User(name: "Up", loginMethods: [.facebook, .instagram], numberOfFriends : 4)
42
67
```
43
68
69
+
That's right. I have 4 friends.
70
+
44
71
### Encode (Object to JSON)
72
+
Let's attempt convert the `bob`object to a `json` format
45
73
46
74
```swift
47
75
//: Create Encoder
48
76
let jsonEncoder =JSONEncoder()
49
77
```
50
78
51
79
#### Customize Encoder
80
+
You may customize how the final form of `json` would look like as shown below. You don't have to.
81
+
52
82
```swift
53
83
jsonEncoder.outputFormatting= .prettyPrinted
54
84
jsonEncoder.dataEncodingStrategy= .base64Encode
55
85
```
56
86
57
87
#### Execution
88
+
Let us convert the `bob` object to `json` using the `jsonEncoder` object.
89
+
58
90
```swift
59
91
//: Encode
60
92
var data: Data?
@@ -70,7 +102,21 @@ catch(let error) {
70
102
}
71
103
```
72
104
105
+
You could technically execute the above method in one line of code using `try!`. But, it's better to handle error so that no one goes wild.
106
+
107
+
```json
108
+
JSON String : {
109
+
"name" : "Up",
110
+
"loginMethods" : [
111
+
"facebook",
112
+
"instagram"
113
+
],
114
+
"numberOfFriends" : 4
115
+
}
116
+
```
117
+
73
118
### Decode (JSON to Object)
119
+
Let's attempt to convert the `json` file to an object using `JSONDecoder`.
74
120
75
121
#### Create Decoder
76
122
```swift
@@ -89,6 +135,25 @@ do {
89
135
}
90
136
```
91
137
138
+
The `bob` local constant has been created within the `do` block based on the type of `User`. The `json` format has to match with the data model structure of the class/struct parameter. If not, you will get an error.
139
+
140
+
### Final Thought
141
+
`JSONEncoder` and `JSONDecoder` are powerful features. However, you still have to be cautious since the data structure of the object must match with that of the json file. If not, it's not great. Make sure you are aware.
[Working with JSON in Swift - Apple](https://developer.apple.com/swift/blog/?id=37)
150
+
151
+
[How to parse Json in Swift - Roadfile Software](http://roadfiresoftware.com/2016/12/how-to-parse-json-with-swift-3/)
152
+
153
+
[Swift JSON Tutorial - Ray Wenderlich](https://www.raywenderlich.com/150322/swift-json-tutorial-2)
154
+
155
+
156
+
## Conclusion
157
+
In this lesson, we haven't learned how to parse and map a `json` file using the old approach since you can find those things anywhere on the internet. In fact, I have attached a couple resources for you to take a look at if you want.
158
+
159
+
However, you've learned how to convert an object to a json file by conforming to the `Codable` protocol. And, you've learned how to map a json file to an object with one line of code. Still, you have to cautious since the blueprint/data structure must match together.
Copy file name to clipboardExpand all lines: source-code/9000_swift4/9004_codable_json.playground/Pages/8001_nested_generics_recursive_enum.xcplaygroundpage/Contents.swift
+4-5
Original file line number
Diff line number
Diff line change
@@ -3,7 +3,7 @@
3
3
### What's New in Swift 4
4
4
### 9004_Codable and JSON Serialization
5
5
6
-
**Problem:** Map JSON to Object in one line of code
6
+
**Problem:** Map JSON to Object in one line of code and the opposite
7
7
8
8
---
9
9
@@ -16,12 +16,11 @@ let republicOfKorea = JSON(dictionary: [
16
16
"name": "Republic of Korea",
17
17
"population": 50000000
18
18
])
19
-
20
-
let koreaCaital: String? = republicOfKorea["capital"]
21
-
let koreaName: String? = republicOfKorea["name"]
22
-
let koreaPopulation: Int? = republicOfKorea["population"]
23
19
*/
24
20
21
+
// Itunes API Doc: https://affiliate.itunes.apple.com/resources/documentation/itunes-store-web-service-search-api/#overview
22
+
// API Call: https://itunes.apple.com/lookup?id=909253
0 commit comments