Với Swift 3 và Swift 4, Stringcó một phương thức gọi là data(using:allowLossyConversion:). data(using:allowLossyConversion:)có tuyên bố sau:
func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?
Trả về Dữ liệu chứa đại diện của Chuỗi được mã hóa bằng mã hóa đã cho.
Với Swift 4, String's data(using:allowLossyConversion:)có thể được sử dụng kết hợp với JSONDecoder' s decode(_:from:)để deserialize một chuỗi JSON thành một cuốn từ điển.
Hơn nữa, với Swift 3 và Swift 4, String's data(using:allowLossyConversion:)cũng có thể được sử dụng kết hợp với JSONSerialization' s jsonObject(with:options:)để deserialize một chuỗi JSON thành một cuốn từ điển.
# 1. Giải pháp Swift 4
Với Swift 4, JSONDecodercó một phương thức gọi là decode(_:from:). decode(_:from:)có tuyên bố sau:
func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable
Giải mã một giá trị cấp cao nhất của loại đã cho từ biểu diễn JSON đã cho.
Mã Playground bên dưới hiển thị cách sử dụng data(using:allowLossyConversion:)và decode(_:from:)để lấy Dictionarytừ JSON được định dạng String:
let jsonString = """
{"password" : "1234", "user" : "andreas"}
"""
if let data = jsonString.data(using: String.Encoding.utf8) {
do {
let decoder = JSONDecoder()
let jsonDictionary = try decoder.decode(Dictionary<String, String>.self, from: data)
print(jsonDictionary) // prints: ["user": "andreas", "password": "1234"]
} catch {
// Handle error
print(error)
}
}
# 2. Giải pháp Swift 3 và Swift 4
Với Swift 3 và Swift 4, JSONSerializationcó một phương thức gọi là jsonObject(with:options:). jsonObject(with:options:)có tuyên bố sau:
class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
Trả về một đối tượng Foundation từ dữ liệu JSON đã cho.
Mã Playground bên dưới hiển thị cách sử dụng data(using:allowLossyConversion:)và jsonObject(with:options:)để lấy Dictionarytừ JSON được định dạng String:
import Foundation
let jsonString = "{\"password\" : \"1234\", \"user\" : \"andreas\"}"
if let data = jsonString.data(using: String.Encoding.utf8) {
do {
let jsonDictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String : String]
print(String(describing: jsonDictionary)) // prints: Optional(["user": "andreas", "password": "1234"])
} catch {
// Handle error
print(error)
}
}