JSON là viết tắt của Javascript Object Notation. Đa phần khi làm việc với API hoặc dịch vụ khác, dữ liệu trả về dạng JSON và cần chuyển đổi sang định dạng ngôn ngữ hỗ trợ.
Framework Foundation của iOS cung cấp lớp JSONSerialization để chuyển JSON sang các định dạng hỗ trợ như Dictionary, String, Bool, v.v.
Lớp JSONSerialization cung cấp phương thức jsonObject(with:options:) phân tích JSON và trả về Any làm kết quả, và lỗi nếu dữ liệu không phân tích được.
// Ví dụ JSON: /* { "age": 42.0, "name": { "firstName": "tut" } } */
Xem ví dụ khác, giả sử nhận dữ liệu từ API, để phân tích dữ liệu này dùng JSONSerialization.jsonObject(with:options:)
if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] { }
// Bây giờ json object chứa dữ liệu nhận được dưới dạng dictionary String:Any, hoặc thoát ra else nếu thất bại.
// Giả sử json chứa khóa "Student" với giá trị là dictionary
guard let student = json["Student"] as? [String: Any] else { return }
Đây là cách phân tích JSON và lấy giá trị. Có thể nâng cao bằng model và initializer. Xem ví dụ tạo file JSON cục bộ và phân tích.
Tạo file JSON với dữ liệu sau và lưu jako exercises.json
{ "Warmup": { "Exercises": [ { "Name": "Neck Strech", "images": [ "http:sdf.com", "sdf", "sdf", "sdf" ], "time": 30 } ] } }
Phân tích file JSON cục bộ và in kết quả:
if let filePath = Bundle.main.path(forResource: "exerciseData", ofType: "json") { do { let data = try Data(contentsOf: URL(fileURLWithPath: filePath), options: .mappedIfSafe) let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) if let exercises = jsonResult as? [String:AnyObject] { if let warmups = exercises["Warmup"] as? [String:AnyObject] { print(warmups) } } } catch { print(error.localizedDescription) } }
Kết quả chạy mã:
