【问题标题】:Swift - Alamofire - Parsing JSONSwift - Alamofire - 解析 JSON
【发布时间】:2015-04-13 17:29:25
【问题描述】:

我目前正在开发一个应用程序,我使用 Alamofire 从 Web 服务检索 JSON。

JSON 看起来像这样 (http://258labs.be/others/getly-webservice/getuserslocations.php):

    [
        {
            "first_name":"Ludo",
            "latitude":"50.8212662023034",
            "longitude":"4.36678815633465"
        },{
            "first_name":"Maxime",
            "latitude":"50.8214004366864",
            "longitude":"4.36678370989307"
        }
    ]

我在网上看过很多用 Swift 解析 JSON 的帖子,不管有没有 Alamofire。而且我从未见过没有标题的 JSON 直接以一堆元组开头。所以我不知道如何解析它

这是我的 Alamofire 代码:

// Get informations from others users

Alamofire.request(.GET, "http://258labs.be/others/getly-webservice/getuserslocations.php").responseJSON() {
    (_, _, data, _) in
    println(data)

    for item in data! as [String: AnyObject] {
        println(item["first_name"])
    }
}

你能告诉我处理这个 JSON 的方法吗?

提前致谢,抱歉如果是转帖,我尝试阅读大部分帖子,但没有一个看起来像这样。

【问题讨论】:

  • 您是否遇到任何错误?

标签: json swift parsing alamofire


【解决方案1】:

看看 SwiftyJSON。它与 Alamofire 搭配得很好

https://github.com/SwiftyJSON/SwiftyJSON

这是我的一种测试方法中的一些代码。

Alamofire.request(.GET, URL)
        .responseJSON { (request, response, json, error) in
            var json = JSON(json!)
            println(json["flights"][0])

            expectation.fulfill()

    }

JSON(json) 调用正在使用 SwiftyJSON 解析数据

所以在您的情况下,您可能需要类似:json["first_name"].string

【讨论】:

    【解决方案2】:

    您的data 是一个字典数组。

      Alamofire.request(.GET, "http://258labs.be/others/getly-webservice/getuserslocations.php").responseJSON() {
        (_, _, data, _) in
        println(data)
    
        if let decoded = data as? [[String: AnyObject]] {
          for dic in decoded {
            println(dic["first_name"])
          }
        }
    
      }
    

    【讨论】:

      猜你喜欢
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 2020-02-23
      • 1970-01-01
      相关资源
      最近更新 更多