JSON使用此URL解析Swift In Swift

时间:2015-05-03 22:37:41

标签: json swift parsing xcode6

寻找有关解析以下链接的建议。

http://www.claritin.com/weatherpollenservice/weatherpollenservice.svc/getforecast/90210

看起来是某种形式的JSON,但我想知道在Swift中提取这些数据的最佳方法是什么。

非常新的快速,所以对此有任何帮助非常感谢。

1 个答案:

答案 0 :(得分:2)

实际上对这个响应要非常小心,因为它可能看起来像JSON字典,但事实并非如此。它是一个JSON字符串,其字符串本身就是JSON字典。

因此,检索它,使用带有NSJSONSerialization选项的.AllowFragments来处理字符串。

然后获取结果字符串,将其转换为数据,现在您可以解析实际的JSON:

let url = NSURL(string: "http://www.claritin.com/weatherpollenservice/weatherpollenservice.svc/getforecast/90210")!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { data, response, error in
    if data != nil {
        var error: NSError?
        if let jsonString = NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments, error: &error) as? String {
            if let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding) {
                if let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as? NSDictionary {
                    println(json)
                } else {
                    println("unable to parse dictionary out of inner JSON: \(error)")
                    println("jsonString = \(jsonString)")
                }
            }
        } else {
            println("unable to parse main JSON string: \(error)")
            println("data = \(NSString(data: data, encoding: NSUTF8StringEncoding))")
        }
    } else {
        println("network error: \(error)")
    }
}

这个JSON表示的JSON字符串是一种奇怪的格式,需要你跳过一些额外的箍。您可能希望联系该Web服务的提供程序,以查看是否有其他格式用于检索此数据(例如,作为简单的JSON响应)。