JSON Parsing In Swift with this url

Look for advice on parsing the following link.

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

It looks like it's some kind of JSON form, but I was wondering what would be the best way to pull this data in Swift.

Very new to fast, so any help on this is greatly appreciated.

+3


source to share


1 answer


Actually, be very careful with this answer as it might look like a JSON dictionary, but it isn't. It is a JSON string for which the string itself is a JSON dictionary.

So, extract it, use NSJSONSerialization

with option .AllowFragments

to process the string.

Then take the resulting string, convert it to data, and now you can parse the actual 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)")
    }
}

      

This JSON string of JSON representation is a curious format that requires you to jump over additional hoops. You can contact the provider of this web service to see if there are other formats to retrieve this data (like a simple JSON response, for example).

+2


source







All Articles