ios – Swift JSON错误:无法将’__NSDictionaryM’类型的值转换为’NSArray’

前端之家收集整理的这篇文章主要介绍了ios – Swift JSON错误:无法将’__NSDictionaryM’类型的值转换为’NSArray’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
从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,我会收到错误

来自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"}]

来自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":"fendy.w@mvig.net","company":"","company_id":"1","company_name":"Simtech"},{"user_id":"3","user_login":"customer","timestamp":"1441604240","firstname":"Customer","lastname":"Customer","email":"customer@example.com","company":"Simtech",{"user_id":"1","user_login":"admin","is_root":"Y","user_type":"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"}}

我认为它的风格是相同的,但为什么不使用网址http://bitnami.local/cscart_demo/api/users.谁有人可以帮忙?

解决方法

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

您需要将json的类型更改为Dictionary< String,AnyObject>,然后反序列化,如下所示:

json = NSJSONSerialization.JSONObjectWithData(data,error: nil) as! Dictionary<String,AnyObject>
原文链接:https://www.f2er.com/iOS/331289.html

猜你在找的iOS相关文章