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.

1
  • 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. Commented May 3, 2015 at 23:04

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.