soy muy nuevo en el análisis de json e intenté analizar un archivo json que tiene una lista de autos, pero cuando lo analizo, da cero
func jsonTwo(){ let url = Bundle.main.url(forResource: "car_list", withExtension: "json")! let data = try! Data(contentsOf: url) let JSON = try! JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] print(".........." , JSON , ".......") let brand = JSON?["models"] as? [[String : Any]] print("=======",brand,"=======") }y cuando hice algunas modificaciones a este código como se muestra a continuación
func jsonTwo(){ let url = Bundle.main.url(forResource: "car_list", withExtension: "json")! let data = try! Data(contentsOf: url) let JSON = try! JSONSerialization.jsonObject(with: data, options: []) print(".........." , JSON , ".......") let brand = JSON["brand"] as? [[String : Any]] print("=======",brand,"=======") }luego aparece un error que dice "El tipo 'Cualquiera' no tiene miembros de subíndice"
a continuación hay una muestra del archivo json que estoy usando
[{"brand": "Aston Martin", "models": ["DB11","Rapide","Vanquish","Vantage"]}]El objeto externo es una matriz, tenga en cuenta el [] y el valor de los models clave es una matriz de cadenas.
func jsonTwo() { let url = Bundle.main.url(forResource: "car_list", withExtension: "json")! let data = try! Data(contentsOf: url) let json = try! JSONSerialization.jsonObject(with: data) as! [[String : Any]] print(".........." , JSON , ".......") for item in json { let brand = item["brand"] as! String let models = item["models"] as! [String] print("=======",brand, models,"=======") } } o más cómodo con Decodable
struct Car: Decodable { let brand : String let models : [String] } func jsonTwo() { let url = Bundle.main.url(forResource: "car_list", withExtension: "json")! let data = try! Data(contentsOf: url) let cars = try! JSONDecoder().decode([Car].self, from: data) for car in cars { let brand = car.brand let models = car.models print("=======",brand, models,"=======") } } ¡Normalmente, se desaconseja encarecidamente forzar el desenvolvimiento de opcionales con ! pero en este caso el código no debe fallar porque un archivo en el paquete de la aplicación es de solo lectura en tiempo de ejecución y cualquier falla revelaría un error de diseño .
Necesitas
struct Root: Codable { let brand: String let models: [String] } do { let url = Bundle.main.url(forResource: "car_list", withExtension: "json")! let data = try Data(contentsOf: url) let res = try JSONDecoder().decode([Root].self, from: data) print(res) } catch { print(error) }tu problema como
let JSON = try! JSONSerialization.jsonObject(with: data, options: []) devuelve Any , por lo que no puede usar subíndices como un diccionario aquí JSON["brand"]
Tenga en cuenta que la variable JSON en su código es una matriz de objetos. Tienes que lanzarlo correctamente.
func jsonTwo(){ let url = Bundle.main.url(forResource: "car_list", withExtension: "json")! let data = try! Data(contentsOf: url) let JSON = try! JSONSerialization.jsonObject(with: data, options: []) print(".........." , JSON , ".......") if let jsonArray = JSON as? [[String: Any]] { for item in jsonArray { let brand = item["brand"] as? String ?? "No Brand" //A default value print("=======",brand,"=======") } } }