Swift JSON error : Could not cast value of type '__NSDictionaryM' to 'NSArray'

后端 未结 3 433
自闭症患者
自闭症患者 2020-12-03 18:45

when decoding JSON from webservice(API) i get error :

Could not cast value of type \'__NSDictionaryM\' (0x1037ad8a8) to \'NSArray\' (0x1037ad470). 


        
相关标签:
3条回答
  • 2020-12-03 19:15

    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
            }
    
    0 讨论(0)
  • 2020-12-03 19:21

    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()
    
    0 讨论(0)
  • 2020-12-03 19:30

    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>
    
    0 讨论(0)
提交回复
热议问题