Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

ios

swift

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

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

My Code :

var kGetURL = "http://bitnami.local/cscart_demo/api/users"

//var kGetURL = "http://localhost/fendy/getjson.php"

var json : Array<AnyObject> = []

 override func viewDidLoad() {
    super.viewDidLoad()
    start()
 }

 func getData(data : NSData){
    //error at this line :
    json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! Array<AnyObject>
    //error
    tableView.reloadData()
}

func start(){ 
    var url : NSURL = NSURL(string: kGetURL)!
    var data : NSData = NSData(contentsOfURL: url)!
    getData(data)
}

if i change url to http://localhost/fendy/getjson.php, its working so nice.

i get error if my url is http://bitnami.local/cscart_demo/api/users

Response from webservice http://localhost/fendy/getjson.php :

 [{"id":"17","Name":"KFC","Message":"awesome"},
{"id":"18","Name":"McDonald","Message":"good"},
{"id":"23","Name":"Burger King","Message":"tasty"},
{"id":"38","Name":"Pizza hut","Message":"yummy"},
{"id":"39","Name":"Steak","Message":"very Delicious"}]

Response from webservice http://bitnami.local/cscart_demo/api/users :

 {"users":
[{"user_id":"4","user_login":"user_4","is_root":"N","timestamp":"1441608048","user_type":"C","status":"A","firstname":"","lastname":"","email":"[email protected]","company":"","company_id":"1","company_name":"Simtech"},
{"user_id":"3","user_login":"customer","is_root":"N","timestamp":"1441604240","user_type":"C","status":"A","firstname":"Customer","lastname":"Customer","email":"[email protected]","company":"Simtech","company_id":"1","company_name":"Simtech"},
{"user_id":"1","user_login":"admin","is_root":"Y","timestamp":"1441604240","user_type":"A","status":"A","firstname":"John","lastname":"Doe","email":"[email protected]","company":"Your company","company_id":"0","company_name":null}],
"params":{"page":1,"items_per_page":"10","sort_order":"asc","sort_by":"name","sort_order_rev":"desc","total_items":"3"}}

i think it's Style is same, but why not working with url http://bitnami.local/cscart_demo/api/users . anyone can help?

like image 822
fendy Avatar asked Sep 07 '15 08:09

fendy


1 Answers

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>
like image 192
Glorfindel Avatar answered Sep 29 '22 00:09

Glorfindel