如何在 Swift 中將 JSON 字串轉換為字典?
Swift 提供了一個名為 JSONSerialization 的類,用於將 JSON 字串轉換為字典格式。例如,您從資料庫接收一個 JSON 字串,為了在應用程式中使用它,您可能需要將其轉換為真正的物件型別。在本文中,您將看到一些關於如何將 JSON 字串轉換為字典的示例。
什麼是 JSON 字串?
JSON 字串是一個被轉換為其他格式(如 base64 或 URL 編碼)的字串。此轉換後的字串可用於網路請求或儲存在資料庫中。此轉換後的字串在傳送請求時提供安全性。此外,您還可以以 JSON 字串格式傳送影像資料。
JSONSerialization
iOS 和 macOS 的 Foundation 框架預設包含 JSONSerialization 類。要建立 Swift 字典或陣列,此類需要一個字串或資料物件。使用相同的類,您還可以將字典或陣列轉換為 JSON 物件。JSONSerialization 類處理序列化和反序列化過程。
示例
在 Swift 中,您可以使用 JSONSerialization 類將 JSON 字串轉換為字典。這是一個示例程式碼片段:
let jsonString = "{"movies":[{"id": 100, "name": "Transformers", "desc": "Desc here."},{"id": 101, "name": "Avengers", "desc": "Desc here 2."},{"id": 102, "name": "Interstellar", "desc": "Desc here 3."}]}" let data = Data(jsonString.utf8) do { // make sure this JSON is in the format we expect if let dictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] { print("Dictionary format: \(dictionary)") } } catch let error as NSError { print("Failed to load: \(error.localizedDescription)") }
輸出
Dictionary format: ["movies": <__NSArrayI 0x600000f3b3f0>( { desc = "Desc here."; id = 100; name = Transformers; }, { desc = "Desc here 2."; id = 101; name = Avengers; }, { desc = "Desc here 3."; id = 102; name = Interstellar; } ) ]
在上面的示例中,我們建立了一個包含一些基本資訊的 JSON 字串,將其轉換為字典格式,最後將 JSON 資料轉換為字典。jsonObject(with:options:) 方法中的 options 引數是可選的。
請注意,如果 JSON 字串包含無法轉換為字典的值,例如自定義物件或迴圈引用,則 jsonObject(with:options:) 方法將丟擲錯誤,並且 do-try-catch 塊內的程式碼將不會執行。
使用擴充套件
還有另一種強烈推薦的方法可以將 JSON 字串轉換為字典。您可以建立一個擴充套件並將這些函式新增到該擴充套件中。這將有助於在您的程式碼庫中全域性訪問這些屬性和方法。
示例
以下是如何使用擴充套件的示例。
extension String { var toDictionary: [String: Any]? { let data = Data(self.utf8) do { // make sure this JSON is in the format we expect if let dictionary = try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed) as? [String: Any] { return dictionary } } catch let error as NSError { print("Failed to load: \(error.localizedDescription)") } return nil } } let jsonString = "{"movies":[{"id": 100, "name": "Transformers", "desc": "Desc here."},{"id": 101, "name": "Avengers", "desc": "Desc here 2."},{"id": 102, "name": "Interstellar", "desc": "Desc here 3."}]}" if let dictionary = jsonString.toDictionary { print("Dictionary format: \(dictionary)") }
輸出
Dictionary format: ["movies": <__NSArrayI 0x600001d63ab0>( { desc = "Desc here."; id = 100; name = Transformers; }, { desc = "Desc here 2."; id = 101; name = Avengers; }, { desc = "Desc here 3."; id = 102; name = Interstellar; } ) ]
結論
在 Swift 中,您可以透過低階 API 將原始 JSON 字串轉換為集合(如陣列或字典)。您可以使用 JSONSerialization 類將原始 JSON 物件轉換為有意義的物件。
此類內置於 Foundation 框架中。您可以在任何平臺(如 iOS、macOS、watchOS 等)上使用此類。此外,反過來,您可以使用反序列化過程將自定義物件轉換回原始 JSON 字串。
在 Swift 4 中,Apple 引入了 Codable 協議,這使得序列化和反序列化過程變得容易。此協議提供了一種靈活的方式來使用 JSON 資料解析資料並將其儲存到模型類/結構體中。此協議可用於輕鬆地將模型物件轉換為 JSON 資料。
Codable 協議有助於減少程式碼並處理序列化和反序列化過程,使程式碼更簡潔且易於維護。