我在使用Swift获取JSON数组时遇到问题。
func getBenefitJSON() -> [AnyObject] {
let urlString = String("https://www.kyfb.com/KYFB/includes/themes/CodeBlue/display_objects/custom/remote/webservices/services.cfc?method=getMemberBenefits")
let url = URL(string: urlString!)
var data = Data()
do {
data = try Data(contentsOf: url!)
} catch {
}
print("URL Data: \(data)")
do {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as! [AnyObject]
print("JSON: \(json)")
return json
} catch {
print("Could not get JSON")
return []
}
}
我从网址获取数据,但返回一个空数组。我做错了什么?
URL Data: 42769 bytes
Could not get JSON
以下是JSON的回复
[{"image":"https://cdn.kyfb.com/KYFB/cache/file/70162997-E06B-E9B6-88514280CA8397CC_medium.jpg","description":"","link":"https://www.kyfb.com/insurance/insurance-products/","name":"KFB Insurance","children":[]}, ...]
以下是错误
UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
我还在jsonlint.com验证了网址的回复
URL数据为字符串:
<wddxPacket version='1.0'><header/><data><string>[{"image":"https://cdn.kyfb.com/KYFB/cache/file/70162997-E06B-E9B6-88514280CA8397CC_medium.jpg","description":"","link":"https://www.kyfb.com/insurance/insurance-products/","name":"KFB Insurance","children":[]}, ...]</string></data></wddxPacket>)
答案 0 :(得分:-1)
我测试了你的代码,如果JSON的顶层是一个数组,它就可以工作了。因此,您想要读取的JSON可能不是数组而是字典。
要阅读词典,您需要将返回类型从[AnyObject]
更改为[String:AnyObject]
以及此类型的所有其他匹配项。
尽管如此,我建议使用SwiftyJSON在Swift中使用JSON。