3

Looking for advice on parsing the following link.

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

Looks to be some form of JSON but I was wondering what would be the best way of pulling this data in Swift.

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

Opei
  • 253
  • 1
  • 2
  • 12
  • It's a JSON object containing two other objects, "pollenForecast" and "weatherForecast". Those objects contain arrays named "forecast" which contain additional details. Understand what the JSON means before you try to map it into code. – Hot Licks May 03 '15 at 23:04

1 Answers1

2

Actually be very careful with that response, as it might look like JSON dictionary, but it's not. It's a JSON string, for which the string, itself, is the JSON dictionary.

So, retrieve it, use NSJSONSerialization with the .AllowFragments option to handle the string.

Then take the resulting string, convert that to a 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, requiring you to jump through some extra hoops. You might want to contact the provider of that web service to see if there are other formats for retrieving this data (e.g. as a simple JSON response).

Rob
  • 415,655
  • 72
  • 787
  • 1,044