gpt4 book ai didi

ios - swift JSON 错误 : Could not cast value of type '__NSDictionaryM' to 'NSArray'

转载 作者:搜寻专家 更新时间:2023-10-30 21:58:28 24 4
gpt4 key购买 nike

从 web 服务 (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 , 它工作得很好。

如果我的 url 是 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 .谁能帮忙?

最佳答案

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

您需要更改 json 的类型至 Dictionary<String, AnyObject> , 反序列化如下:

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

关于ios - swift JSON 错误 : Could not cast value of type '__NSDictionaryM' to 'NSArray' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32434753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com