when decoding JSON from webservice(API) i get error :
Could not cast value of type \'__NSDictionaryM\' (0x1037ad8a8) to \'NSArray\' (0x1037ad470).
try cache for Serialization
do {
if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String : Any] { // as? data type
if let otherDict = json["dataKey"] as? [String : Any] {
//do something
}
}
} catch {
// can't json serialization
}
Your method is casting JSON result to an array. It works fine with the URL that returns an array represented as JSON, but it does not work with the URL that returns a dictionary, not an array, represented as JSON.
Although the "style" of returned values looks the same, the second one is a one-item dictionary. What you probably want is to extract the "users"
element from it, which is an array.
If you do not know which of the two URLs you are getting, you could try both styles with as?
cast instead of as!
:
let tmp : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil)
if let arr = tmp as? Array<AnyObject> {
json = arr
} else if dict = tmp as? [String: AnyObject] {
json = dict["users"] as! Array<AnyObject>
} else {
// Handle an error: the input was unexpected
}
tableView.reloadData()
The bitnami response starts with a {
and it is therefore a JSON object, which corresponds to an NSDictionary
. The other one starts with [
which indicates an array.
You need to change the type of json
to Dictionary<String, AnyObject>
, and deserialize as follows:
json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! Dictionary<String, AnyObject>