I am working on an iOS app in Swift 3, and I make a call to a server and get json back and serialize it.
When I try to parse it I get this error:
"Could not cast value of type '__NSArrayI' (0x1a779acc8) to 'NSDictionary' (0x1a779b128). 2017-03-16 09:53:00.710776 AutoBuddy[3164:706970] Could not cast value of type '__NSArrayI' (0x1a779acc8) to 'NSDictionary' (0x1a779b128)."
I have seen a couple other versions of this question, but I am still confused. From what I can tell, the JSON comes back as a dictionary with key value pairs [String:Any].
I tried explicitly casting the result of the call "as? Dictionary< String, Any > but that failed. It doesn't make sense to me, because I appear to be getting a dictionary, but it doesn't behave as one. Currently the program is crashing on the first line of my parseJSON function. I have a feeling that the problem is either how I am getting the json back, or how I serialize it, because I have used a similar parsing method before and it always worked. Or if it is a parsing problem, could someone explain to me the proper way to parse this out? I will post the code and an example of the JSON that it serializes.
JSON:
["id": 745, "year": 1995, "styles": <__NSArrayI 0x170e68f00>(
{
id = 7654;
name = "2dr Coupe";
submodel = {
body = Coupe;
modelName = "Mustang Coupe";
niceName = coupe;
};
trim = Base;
},
{
id = 7653;
name = "2dr Convertible";
submodel = {
body = Convertible;
modelName = "Mustang Convertible";
niceName = convertible;
};
trim = Base;
},
{
id = 7648;
name = "GT 2dr Coupe";
submodel = {
body = Coupe;
modelName = "Mustang Coupe";
niceName = coupe;
};
trim = GT;
},
{
id = 7647;
name = "GT 2dr Convertible";
submodel = {
body = Convertible;
modelName = "Mustang Convertible";
niceName = convertible;
};
trim = GT;
},
{
id = 7650;
name = "GTS 2dr Coupe";
submodel = {
body = Coupe;
modelName = "Mustang Coupe";
niceName = coupe;
};
trim = GTS;
}
)
]
Swift Code:
func getJSONData(path: String)
{
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = URL(string: path + "API key")!
let task = session.dataTask(with: url, completionHandler:
{
(data, response, error) in
if error != nil
{
print(error!.localizedDescription)
}
else
{
do {
if let resultJSON = try JSONSerialization.jsonObject(with: data!) as? [String: Any]
{
print(resultJSON)
self.parseJSON(json: resultJSON)
}
}
catch
{
print("\(error)")
}
}
})
task.resume()
}
func parseJSON(json: [String: Any])
{
let styles = json["styles"] as! [String:Any] // Crashes Here
print(styles)
let names = styles["name"] as! String
print(names)
}