在Swift中將字典轉換為JSON
Swift提供了一個名為JSONSerialization的類,用於將字典轉換為JSON字串。我們將使用兩個步驟在Swift語言中將字典轉換為JSON字串。步驟如下:
使用JSONSerialization.data()方法將字典轉換為JSON資料格式,該方法將字典物件作為引數以及選項。
現在,使用String(data:encoding:)建構函式將JSON資料轉換為JSON字串格式。
在本文中,您將看到一些將字典轉換為JSON字串的示例。
JSONSerialization
iOS和macOS的Foundation框架預設包含JSONSerialization類。要建立Swift字典或陣列,此類需要字串或資料物件。使用相同的類,您還可以將字典或陣列轉換為JSON物件。JSONSerialization類處理序列化和反序列化過程。
以下是將字典轉換為JSON字串的示例
步驟1 - 建立一個全域性函式,該函式將字典作為引數進行轉換。
步驟2 - 使用data(withJSONObject:options:)方法將字典轉換為JSON資料格式。
步驟3 - 在此方法中處理失敗的情況,因為data()方法返回一個可選的資料值。
步驟4 - 使用String(data:encoding)方法將JSON資料轉換為JSON字串。
步驟5 - 處理失敗的情況,因為此方法返回一個可選的字串值。
import Foundation
func convertDictionaryToJSON(_ dictionary: [String: Any]) -> String? {
guard let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted) else {
print("Something is wrong while converting dictionary to JSON data.")
return nil
}
guard let jsonString = String(data: jsonData, encoding: .utf8) else {
print("Something is wrong while converting JSON data to JSON string.")
return nil
}
return jsonString
}
let dictionary: [String: Any] = ["name": "John Allen", "age": 32, "company": "Google Inc."]
if let output = convertDictionaryToJSON(dictionary) {
print("Input dictionary: \(dictionary)")
print("Output JSON: \(output)")
}
輸出
Input dictionary: ["age": 32, "name": "John Allen", "company": "Google Inc."]
Output JSON: {
"age" : 32,
"name" : "John Allen",
"company" : "Google Inc."
}
請注意,如果字典包含無法轉換為JSON的值,例如自定義物件或迴圈引用,則data(withJSONObject:options:)方法將丟擲錯誤,並且do-try-catch塊內的程式碼將不會執行。
使用擴充套件
還有另一種強烈推薦的方法可以將字典轉換為JSON字串。您可以建立一個擴充套件,並將這些函式新增到該擴充套件中。這將有助於在您的程式碼庫中全域性訪問這些屬性和方法。以下是如何使用擴充套件的示例。
擴充套件
import Foundation
extension Dictionary {
var jsonData: Data? {
return try? JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted])
}
func toJSONString() -> String? {
if let jsonData = jsonData {
let jsonString = String(data: jsonData, encoding: .utf8)
return jsonString
}
return nil
}
}
用法
func convertDictionaryToJSON() {
let dictionary: [String: Any] = ["name": "John Allen", "age": 32, "company": "Google Inc."]
guard let jsonData = dictionary.jsonData else {
print("Something is wrong while converting dictionary to JSON data.")
return
}
guard let jsonString = dictionary.toJSONString() else {
print("Something is wrong while converting JSON data to JSON string.")
return
}
print("Input dictionary: \(dictionary)")
print("Output JSON: \(jsonString)")
}
convertDictionaryToJSON()
輸出
Input dictionary: ["age": 32, "company": "Google Inc.", "name": "John Allen"]
Output JSON: {"age" : 32, "company" : "Google Inc.", "name" : "John Allen"}
結論
在Swift中,您可以透過低階API將原始JSON資料轉換為集合,例如陣列或字典。您可以使用JSONSerialization類將原始JSON物件轉換為有意義的物件。此類內置於Foundation框架中。您可以在任何平臺上使用此類,例如iOS、macOS、watchOS等。此外,反過來,您可以使用反序列化過程將自定義物件轉換回原始JSON資料。
在Swift 4中,Apple引入了Codable協議,使序列化和反序列化過程變得容易。此協議提供了一種靈活的方式來使用JSON資料將資料解析並存儲到模型類/結構體中。此協議可用於輕鬆地將模型物件轉換為JSON資料。
Codable協議有助於減少程式碼並處理序列化和反序列化過程,使程式碼更簡潔易維護。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP