【发布时间】:2016-09-07 13:11:03
【问题描述】:
我在使用 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 获取数据,但返回一个空数组。我做错了什么?
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>)
【问题讨论】:
-
最好实际捕获错误以查看发生了什么。
-
该网址是否可达?
-
@RomanPodymov 是的,可以访问。
-
您是如何获得打印的 JSON 的?是来自
data的完整 JSON 吗? -
@Larme 通过在浏览器中访问 URL。