无法使用AlamoFire和SwiftyJSON解析JSON

时间:2016-08-09 15:53:24

标签: ios json swift alamofire swifty-json

我坚持使用AlamoFireSwiftyJSON为iOS解析JSON。我有一个像这样的JSON:

[{"id":23561,"name":"RFI - Persan رادیو صدای Ùرانسه Ùارسی","country":"FR","image":{"url":null,"thumb":{"url":null}},"slug":"rfi-persan-رادیو-صدای-Ùرانسه-Ùارسی","website":"rfi","twitter":"","facebook":"","categories":[{"id":21,"title":"News","description":"","slug":"news","ancestry":"4"}],"streams":[{"stream":"http://rfi-persan.scdn.arkena.com/rfienpersan.mp3","bitrate":0,"content_type":"audio/mpeg","status":1}],"created_at":"2016-01-12T07:52:08+01:00","updated_at":"2016-08-02T01:52:50+02:00"}]

这是我到目前为止所尝试的,但不起作用:

func loadSomeJSONData() {
        Alamofire.request(.GET, "http://example.com/json/")
            .responseJSON { (_, _, data, _) in
                let json = JSON(data!)
                if let Name = json["name"].string {
                    println("name: \(firstName)") // Name should equal "RFI"
                }
        }
    }

但由于某种原因,它没有从json对象获取名称。

非常感谢!

1 个答案:

答案 0 :(得分:3)

你的json是Array而不是Dictionary,所以以这种方式访问​​json

if let arr = json.arrayObject as? [[String:AnyObject]] { 
    if let name = arr[0]["name"] as? String {
        println("name: \(name)") // Name should equal "RFI"
    }
}