小编典典

Swift JSON错误:无法将类型'__NSDictionaryM'的值强制转换为'NSArray'

swift

从webservice(API)解码JSON时出现错误:

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

我的代码:

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)
}

如果我将URL更改为http://localhost/fendy/getjson.php,它的工作原理很好。

如果我的网址是http://bitnami.local/cscart_demo/api/users,我会收到错误消息

来自网络服务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"}]

来自网络服务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":"fendy.w@mvig.net","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":"customer@example.com","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":"robby@mvig.net","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"}}

我认为它的样式是相同的,但是为什么不使用url
http://bitnami.local/cscart_demo/api/users。有人可以帮忙吗?


阅读 468

收藏
2020-07-07

共1个答案

小编典典

bitnami响应以开头,{因此它是一个JSON对象,对应于NSDictionary。另一个以[表示数组。

您需要将的类型更改jsonDictionary<String, AnyObject>,并按如下所示反序列化:

json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! Dictionary<String, AnyObject>
2020-07-07