所有文章

Swift · Codable

解決實務中 Codable 的相關問題

實務上處理 Codable 的常見情境:命名轉換、enum、null 或缺少欄位、巢狀 JSON,以及繼承。

本篇目錄 · 7 個章節

本篇會記錄目前個人在開發過程中,處理 Codable 相關的問題的情境,按簡單到複雜排序,並提出對應的解決方式供大家參考:

  1. 處理 JSON 和 Model 間的命名
  2. 處理 enum 的轉換
  3. 處理 JSON 中 null 或 missing
  4. 處理 JSON 複雜階層關係
  5. 處理 Codable object 繼承關係

前言

在 Codable 尚未出世之前,要解析 HTTP Response 需要用 JSONSerialization 或是 Third-party(比如說 ObjectMapper),寫起來較為冗長,需要處理 JSON 的每一個階層,轉換形態和處理 Optional:

let jsonData = """
{
"data": [
{
"name": "Andy",
"age": 20
},
{
"name": "Bob",
"age": 30
}
]
}
""".data(using: .utf8)!
struct User {
let name: String
let age: Int
}
func sample() {
guard
let jsonObject = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any],
let users = jsonObject["data"] as? [[String: Any]]
else {
return
}
for user in users {
let name = (user["name"] as? String) ?? "Unknown"
let age = (user["age"] as? Int) ?? 0
let user = User(name: name, age: age)
print("🔴", user)
}
}
sample()
/*
Output:
🔴 User(name: "Andy", age: 20)
🔴 User(name: "Bob", age: 30)
*/

大約是在 2017 年 9 月,在 Swift4 推出 Codable,解析 JSON 這件事變得方便:

struct User: Codable {
let name: String
let age: Int
}
struct UserData: Codable {
let data: [User]
}
func sample() {
guard let userData = try? JSONDecoder().decode(UserData.self, from: jsonData) else { return }
for user in userData.data {
print("🔴", user)
}
}
sample()
/*
Output:
🔴 User(name: "Andy", age: 20)
🔴 User(name: "Bob", age: 30)
*/

補充,也可以透過一些工具幫助我們將 JSON 快速產生出 Model,像是 app.quicktype.io。

處理 JSON 和 Model 間的命名

Server 端習慣用 Snake Case 作為命名習慣(以底線做區隔,如說 first_name),在 Swift 當中更習慣於 Camel Case(駝峰式命名)來命名,這時就需要定義 key 對應到的變數,需要建立一個 enum 類型 conform CodingKey protocol 來對應:

let jsonData = """
{
"first_name": "Bing",
"last_name": "Kuo",
"age": 20
}
""".data(using: .utf8)!
struct User: Codable {
let firstName: String
let lastName: String
let age: Int
enum CodingKeys: String, CodingKey {
case firstName = "first_name"
case lastName = "last_name"
case age
}
}
func sample() {
guard let user = try? JSONDecoder().decode(User.self, from: jsonData) else { return }
print("🔴", user)
}
sample()
/*
Output:
🔴 User(firstName: "Bing", lastName: "Kuo", age: 20)
*/

另一種方式,可以修改 JSONDecoder 定義好的 keyDecodingStrategy 屬性達到一樣的效果:

struct User: Codable {
let firstName: String
let lastName: String
let age: Int
}
func sample() {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
guard let user = try? decoder.decode(User.self, from: jsonData) else { return }
print("🔴", user)
}
sample()
/*
Output:
🔴 User(firstName: "Bing", lastName: "Kuo", age: 20)
*/

這方法只適用於符合 Snake Case 和 Camel Case命名規範的情況下,如果是要改名成不同的名稱,就一定得建立 CodingKeys。

處理 enum 的轉換

遇到定義好的字串或是數字要轉換成 enum 是比較簡單的,只要 enum conform Codable 跟對應的 RawRepresentable (擁有 Raw Value) 即可:

let jsonData = """
{
"first_name": "Bing",
"last_name": "Kuo",
"age": 20,
"role": "admin"
}
""".data(using: .utf8)!
enum Role: String, Codable {
case admin
case viewer
}
struct User: Codable {
let firstName: String
let lastName: String
let age: Int
let role: Role
}
func sample() {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
guard let user = try? decoder.decode(User.self, from: jsonData) else { return }
print("🔴", user)
}
sample()
/*
Output:
🔴 User(firstName: "Bing", lastName: "Kuo", age: 20, role: __lldb_expr_50.Role.admin)
*/

處理 JSON 中 null 或 missing

這類型的情境有幾種:

  1. JSON 本身可能會是 null,解碼後希望 Model 也保持 optional
  2. JSON 資料結構是動態的,有時會出現,有時不會出現,解碼後希望 Model 也保持 optional
  3. 符合以上兩種情境,但解碼後希望 null 或 missing 時有預設值

第一種情境最為單純,只需要將 property 改為 optional 即可:

let jsonData = """
{
"first_name": "Andy",
"last_name": null,
"age": 20,
"role": "admin"
}
""".data(using: .utf8)!
struct User: Codable {
let firstName: String
let lastName: String? // HERE
let age: Int
let role: Role
}

第二種情境,跟情境一的解決方式相同,只要將可能會是 null 的欄位設定為 optional 即可:

let jsonData = """
[
{
"first_name": "Bing",
"last_name": "Kuo",
"age": 20,
"role": "admin"
},
{
"first_name": "Andy"
}
]
""".data(using: .utf8)!
struct User: Codable {
let firstName: String
let lastName: String?
let age: Int?
let role: Role?
}

第三種情境,有時候雖然 JSON 定義為 optional,但在 client 可能為了商業邏輯或是程式簡潔(後續使用資料不用處理 optional)的情況下想設定為 non-optional,這時就必須要自行實作 init(from:):

struct User: Codable {
let firstName: String
let lastName: String // non-optional
let age: Int
let role: Role
enum CodingKeys: String, CodingKey {
case firstName, lastName, age, role
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
firstName = try container.decode(String.self, forKey: .firstName)
// HERE
lastName = try container.decodeIfPresent(String.self, forKey: .lastName) ?? "<default value>"
age = try container.decode(Int.self, forKey: .age)
role = try container.decode(Role.self, forKey: .role)
}
}

使用 decodeIfPresent 去解析可能會是 null 的欄位,並給予預設值,另一種方式,你可以把 try 改成 try?,這樣 decode failed 就會變成 nil,兩種作法以結果來說是相同的,但過程不一樣,若是確定有 null 的情況下,會傾向前者的做法。

處理 JSON 複雜階層關係

有時候收到的 JSON 有多層的巢狀關係,比如下面這個例子:

{
"user": {
"name": "John",
"age": 20,
"contact": {
"email": "john@example.com",
"phone": "+1234567890"
}
}
}

如果按照 app.quicktype.io 提供的做法,我們可能會產生三個 struct。

struct UserResponse: Codable {
let user: User
}
struct User: Codable {
let name: String
let age: Int
let contact: Contact
}
struct Contact: Codable {
let email, phone: String
}

這樣雖然清楚明了,但有時在專案中未必需要這麼多的 Model,有時要替 Model 想名字也是很頭痛,可以利用 nestedContainer 把巢狀結構整理成較為簡單的資料結構:

let jsonData = """
{
"user": {
"name": "John",
"age": 20,
"contact": {
"email": "john@example.com",
"phone": "+1234567890"
}
}
}
""".data(using: .utf8)!
struct User: Codable {
let name: String
let age: Int
let email: String
let phone: String
// level 1
enum CodingKeys: String, CodingKey {
case user
}
// level 2
enum UserCodingKeys: String, CodingKey {
case name, age, contact
}
// level 3
enum ContactCodingKeys: String, CodingKey {
case email, phone
}
init(from decoder: Decoder) throws {
// level 1: { user }
let container = try decoder.container(keyedBy: CodingKeys.self)
// level 2: user: { ... }
guard let userContainer = try? container.nestedContainer(keyedBy: UserCodingKeys.self, forKey: .user)
else {
throw DecodingError.keyNotFound(
CodingKeys.user,
DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Failed to find 'user' key while decoding.")
)
}
name = try userContainer.decode(String.self, forKey: .name)
age = try userContainer.decode(Int.self, forKey: .age)
// level 3: contact: { ... }
guard let contactContainer = try? userContainer.nestedContainer(keyedBy: ContactCodingKeys.self, forKey: .contact)
else {
throw DecodingError.keyNotFound(
UserCodingKeys.contact,
DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Failed to find 'contact' key while decoding.")
)
}
email = try contactContainer.decode(String.self, forKey: .email)
phone = try contactContainer.decode(String.self, forKey: .phone)
}
}

這樣 decode 部份就完成了,這時 compiler 會因為無法自動解析 encode(to:) 方法而顯示Type ‘User’ does not conform to protocol ‘Encodable’,我們必須自行定義,假設希望 encode 時能呈現一樣的 JSON 格式,可以這樣寫:

func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
var userContainer = container.nestedContainer(keyedBy: UserCodingKeys.self, forKey: .user)
try userContainer.encode(name, forKey: .name)
try userContainer.encode(age, forKey: .age)
var contactContainer = userContainer.nestedContainer(keyedBy: ContactCodingKeys.self, forKey: .contact)
try contactContainer.encode(email, forKey: .email)
try contactContainer.encode(phone, forKey: .phone)
}

為了驗證 decoding 跟 encoding 的結果是否一致,撰寫 prettyString() 來印出 Data 轉 JSON 的樣子,驗證結果:

// Helper function
extension Data {
/// Transform Data type to JSON String
func prettyString() -> String? {
guard
let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedJson = String(data: data, encoding: .utf8)
else { return nil }
return prettyPrintedJson
}
}
func sample() {
// decode
guard let user = try? JSONDecoder().decode(User.self, from: jsonData) else { return }
print("🔴", user)
// encode
let encodedUser = try? JSONEncoder().encode(user)
let jsonString = encodedUser?.prettyString() ?? ""
print("🔴 JSON:\n", jsonString)
}
sample()
/*
Output:
🔴 User(name: "John", age: 20, email: "john@example.com", phone: "+1234567890")
🔴 JSON:
{
"user" : {
"name" : "John",
"age" : 20,
"contact" : {
"email" : "john@example.com",
"phone" : "+1234567890"
}
}
}
*/

處理多種類型的 JSON 資料格式

這類情境的 JSON 通常包含一個 Array,其中都是相關的物件,可能是訊息資料、表單問題資料、影片資料…等,如果這些資料都符合相同的資料結構,就可以用 decode([CodableObject].self, from: data) 的方式處理。

如果,Array 裡面的資料結構不盡相同,就沒辦法用以上方式處理,以訊息的例子舉例,所有訊息都會有 ID 、發送者、發送時間,類型會有文字訊息、貼圖、公告…等,不同類型通常會擁有不同的資訊,比如文字訊息會有文字內容、貼圖訊息會有圖片,像是以下這樣:

[
{
"id": "43039ACC-66DE-4EA8-AC11-2767A648EBD0",
"type": "text",
"sender": "Alice",
"sent_at": "2024-03-02T12:00:00Z",
"textInfo": {
"content": "Hi there!"
}
},
{
"id": "F9D9A7E0-1997-4A92-B76C-70018E1BFBFD",
"type": "sticker",
"sender": "Bob",
"sent_at": "2024-03-02T12:05:00Z",
"stickerInfo": {
"url": "https://example.com/stickers/wave.png",
"description": "Waving hand"
}
}
]

直覺的想法是將各種類型都集中到一個 Message Model,並以 null 方式處理,寫起來會像這樣:

enum MessageType: String, Codable {
case text
case sticker
}
struct Message: Codable {
let id, sender: String
let type: MessageType
let sentAt: Date
let textInfo: TextInfo?
let stickerInfo: StickerInfo?
// There will be more and more properties in the future
enum CodingKeys: String, CodingKey {
case id, type, sender
case sentAt = "sent_at"
case textInfo, stickerInfo
}
}
struct StickerInfo: Codable {
let url: String
let description: String
}
struct TextInfo: Codable {
let content: String
}

但考慮到 MessageType 會有數十幾種,並且未來會持續擴張,在這情況下讓 Message 擁有很多未使用到的 properties 似乎不是好作法,另一種做法,將共用的部分獨立成 superclass,其餘部分用繼承的方式去擴充,寫法如下:

class BasicMessage: Codable {
let type: MessageType
let id: String
let sender: String
let sentAt: Date
enum CodingKeys: String, CodingKey {
case type, id, sender
case sentAt = "sent_at"
}
}
class TextMessage: BasicMessage {
let textInfo: TextInfo
enum TextCodingKeys: String, CodingKey {
case textInfo
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: TextCodingKeys.self)
textInfo = try container.decode(TextInfo.self, forKey: .textInfo)
try super.init(from: decoder)
}
struct TextInfo: Codable {
let content: String
}
}
class StickerMessage: BasicMessage {
let stickerInfo: StickerInfo
enum StickerCodingKeys: String, CodingKey {
case stickerInfo
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StickerCodingKeys.self)
stickerInfo = try container.decode(StickerInfo.self, forKey: .stickerInfo)
try super.init(from: decoder)
}
struct StickerInfo: Codable {
let url: String
let description: String
}
}

預期 [BasicMessage] 後可以在 casting 成其他 subclass:

func sample() {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
guard let messages = try? decoder.decode([BasicMessage].self, from: jsonData) else { return }
for message in messages {
if let textMessage = message as? TextMessage {
print("🔴 Text Message")
} else if let stickerMessage = message as? StickerMessage {
print("🔴 Sticker Message")
} else {
print("🔴 Can't cast to any subclasses.")
}
}
}
sample()
/*
Output:
🔴 Can't cast to any subclasses.
🔴 Can't cast to any subclasses.
*/

結果並不符合預期,因為一旦轉成 BasicMessage,並不會知道原本是 TextMessage 或是 StickerMessage 。

補充,decoder.dateDecodingStrategy 是來解析資料中 Date 的格式,這裡採用的是 ISO 8601,其他還有 secondsSince1970, formatted 或是 custom 可以選

所以換個方向,我們在 decode 時先轉換成 subclass,要達到這樣效果,我們需要先定義一個 MessageData 來負責 decode Array 的流程:

struct MessageData: Codable {
private(set) var messages: [BasicMessage]
init(from decoder: Decoder) throws {
messages = [BasicMessage]()
var container = try decoder.unkeyedContainer()
while !container.isAtEnd {
if let textMessage = try? container.decode(TextMessage.self) {
messages.append(textMessage)
} else if let stickerMessage = try? container.decode(StickerMessage.self) {
messages.append(stickerMessage)
}
}
}
}

JSON 最外層是 Array,所以建立一個 messages: [BasicMessage] 存放,Array 是沒有 key 的,所以使用 decoder.unkeyedContainer() 去建立 container,搭配 !container.isAtEnd 去判斷 Array 是否結束,並迴圈當中去嘗試 casting 成各種 Message Type,若是成功就加入到 messages 當中:

func sample() {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
guard let messageData = try? decoder.decode(MessageData.self, from: jsonData) else { return }
for message in messageData.messages {
if let textMessage = message as? TextMessage {
print("🔴 Text Message")
} else if let stickerMessage = message as? StickerMessage {
print("🔴 Sticker Message")
} else {
print("🔴 Can't cast to any message subclasses.")
}
}
}
sample()
/*
Output:
🔴 Text Message
🔴 Sticker Message
*/

總結

雖然可能會有人說『Backend 回傳符合 Client 需求的結構就好了呀!』,當然這是理想情況下,但現實中會因為各種原因難以實現,可能因為 Backend 程式的 legacy code 無法輕易達成、或是串接的是 third-party 沒辦法配合修改、甚至是組織內部的政治因素…等原因,所以多一些工具隨時能派上場也是好的。

以上就是本篇內容,感謝閱讀。