【问题标题】:Trouble Getting JSON Array获取 JSON 数组时遇到问题
【发布时间】: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。

标签: ios json swift swift3


【解决方案1】:

我测试了您的代码,如果 JSON 的顶层是一个数组,它就可以工作。所以你要读取的 JSON 可能不是数组而是字典。

要阅读字典,您需要将返回类型从 [AnyObject] 更改为 [String:AnyObject] 以及此类型的所有其他匹配项。

尽管如此,我还是建议使用 SwiftyJSON 在 Swift 中使用 JSON。

【讨论】:

  • 我已将部分 JSON 添加到我的问题中。顶层是一个数组。
猜你喜欢
  • 1970-01-01
  • 2015-01-30
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 2019-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多