我正在开发一个应用程序,我使用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的方法吗?
提前致谢和对不起如果这是一个重新发布,我试着阅读大部分帖子,但没有一个看起来像这样。
答案 0 :(得分: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
答案 1 :(得分:0)
您的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"])
}
}
}