Tarek Tarek - 2 months ago 25
Swift Question

Best practice to parse JSON in Swift, OOP-wise

So far I have a model class and a helper class that will download the data using Alamofire.
My question is, where should I parse the data and assign it to the model's object? Should it be done in the model itself or in the helper class or some where else? I'm trying to do what's considered "best practice"
Thanks :)

Answer

If your class has a meaning, it deserved to be a class, so classes as serializing and parsing should be a classes, from my opinion, and is suits OOP well.

With that sad, there are frameworks written for this purpose to make your life easier, so you do not need to handle this by your self, for instance "ObjectMapper" has an extension for Alamofire named "AlamofireObjectMapper".

https://github.com/tristanhimmelman/AlamofireObjectMapper

And you can use it like so:

let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/d8bb95982be8a11a2308e779bb9a9707ebe42ede/sample_json"
Alamofire.request(.GET, URL).responseObject { (response: Response<WeatherResponse, NSError>) in

    let weatherResponse = response.result.value
    print(weatherResponse?.location)

    if let threeDayForecast = weatherResponse?.threeDayForecast {
        for forecast in threeDayForecast {
            print(forecast.day)
            print(forecast.temperature)           
        }
    }
}
Comments