Skip to content

Commit 5ec433b

Browse files
author
Bob Lee
committed
Prepped codable-json file
1 parent 860a732 commit 5ec433b

File tree

4 files changed

+75
-11
lines changed

4 files changed

+75
-11
lines changed

course/swift4/codable-json.md

+71-6
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,55 @@
11
# Codable and JSON Serialization
22
## 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+
35
## Problem
4-
Map JSON to Object in one line of code
6+
Map JSON to Object in one line of code and the opposite
57

6-
## Conclusion
8+
9+
### Introducing JSON
10+
How to resemble a `json` file as seen in the previous lesson.
711

812
```swift
913
let republicOfKorea = JSON(dictionary: [
1014
"capital": "Seoul",
1115
"name": "Republic of Korea",
1216
"population": 50000000
1317
])
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,
1431

15-
let koreaCaital: String? = republicOfKorea["capital"]
16-
let koreaName: String? = republicOfKorea["name"]
17-
let koreaPopulation: Int? = republicOfKorea["population"]
32+
```json
33+
{
34+
"resultCount":1,
35+
"results": [
36+
{"wrapperType":"artist", "artistType":"Artist", "artistName":"Jack Johnson", "artistLinkUrl":"https://itunes.apple.com/us/artist/jack-johnson/id909253?uo=4", "artistId":909253, "amgArtistId":468749, "primaryGenreName":"Rock", "primaryGenreId":21}]
37+
}
1838
```
1939

40+
Let us attempt to convert an object to a json format using the `encode` API introduced in Swift 4.
41+
2042
### Import Foundation
43+
First thing first, import `Foundation`.
44+
2145
```swift
2246
import Foundation
2347
```
2448

2549
### Design Model
50+
Let us create a blueprint for an object.
2651

27-
```
52+
```swift
2853
struct User: Codable {
2954
var name : String
3055
var loginMethods : [LoginMethods]
@@ -41,20 +66,27 @@ enum LoginMethods: String, Codable {
4166
let bob = User(name: "Up", loginMethods: [.facebook, .instagram], numberOfFriends : 4)
4267
```
4368

69+
That's right. I have 4 friends.
70+
4471
### Encode (Object to JSON)
72+
Let's attempt convert the `bob`object to a `json` format
4573

4674
```swift
4775
//: Create Encoder
4876
let jsonEncoder = JSONEncoder()
4977
```
5078

5179
#### Customize Encoder
80+
You may customize how the final form of `json` would look like as shown below. You don't have to.
81+
5282
```swift
5383
jsonEncoder.outputFormatting = .prettyPrinted
5484
jsonEncoder.dataEncodingStrategy = .base64Encode
5585
```
5686

5787
#### Execution
88+
Let us convert the `bob` object to `json` using the `jsonEncoder` object.
89+
5890
```swift
5991
//: Encode
6092
var data: Data?
@@ -70,7 +102,21 @@ catch(let error) {
70102
}
71103
```
72104

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+
73118
### Decode (JSON to Object)
119+
Let's attempt to convert the `json` file to an object using `JSONDecoder`.
74120

75121
#### Create Decoder
76122
```swift
@@ -89,6 +135,25 @@ do {
89135
}
90136
```
91137

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.
142+
92143
### Source Code
93144
[9004_json_serialization_codable]()
145+
94146
### Resources
147+
[Itunes JSON API](https://affiliate.itunes.apple.com/resources/documentation/itunes-store-web-service-search-api/#overview)
148+
149+
[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.

source-code/9000_swift4/.DS_Store

0 Bytes
Binary file not shown.

source-code/9000_swift4/9004_codable_json.playground/Pages/8001_nested_generics_recursive_enum.xcplaygroundpage/Contents.swift

+4-5
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
### What's New in Swift 4
44
### 9004_Codable and JSON Serialization
55

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
77

88
---
99

@@ -16,12 +16,11 @@ let republicOfKorea = JSON(dictionary: [
1616
"name": "Republic of Korea",
1717
"population": 50000000
1818
])
19-
20-
let koreaCaital: String? = republicOfKorea["capital"]
21-
let koreaName: String? = republicOfKorea["name"]
22-
let koreaPopulation: Int? = republicOfKorea["population"]
2319
*/
2420

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
23+
2524

2625
//: Import Foundation
2726
import Foundation

0 commit comments

Comments
 (0)