If you are using Alamofire for Networking in Swift, this article will be helpful for you.

AlamofireObjectMapper is an extension to Alamofire which automatically converts JSON response data into swift objects using ObjectMapper

AlamofireObjectMapper can be installed via Cocoapods or Carthage.

Usage

Example 1 :

Given a URL which returns weather data in the following form:

{
    "location": "Toronto, Canada",    
    "three_day_forecast": [
        { 
            "conditions": "Partly cloudy",
            "day" : "Monday",
            "temperature": 20 
        },
        { 
            "conditions": "Showers",
            "day" : "Tuesday",
            "temperature": 22 
        },
        { 
            "conditions": "Sunny",
            "day" : "Wednesday",
            "temperature": 28 
        }
    ]
}

You can use the extension as the follows:

import AlamofireObjectMapper  

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

    let weatherResponse = response.result.value  //getting JSON response here
    print(weatherResponse?.location)
    
    if let threeDayForecast = weatherResponse?.threeDayForecast {
        for forecast in threeDayForecast {
            print(forecast.day)
            print(forecast.temperature)           
        }
    }
}

The WeatherResponse object in the completion handler is a custom object which you define. The only requirement is that the object must conform to ObjectMapper’s Mappable protocol. In the above example, the  WeatherResponseobject looks like the following:

import ObjectMapper

class WeatherResponse: Mappable {
    var location: String?  //taking string as location key is String value ex. "Toronto, Canada" 
    var threeDayForecast: [Forecast]?  // we are creating another object Forecast and passing array oh that object  
    
	required init?(map: Map){

	}
    
    func mapping(map: Map) {
        location <- map["location"]
        threeDayForecast <- map["three_day_forecast"]
    }
}

class Forecast: Mappable {
    var day: String? //taking string as day string is string
    var temperature: Int? //taking string as day string is string
    var conditions: String?
    
	required init?(map: Map){

	}
    
    func mapping(map: Map) {
        day <- map["day"]
        temperature <- map["temperature"]
        conditions <- map["conditions"]
    }
}

Example 2 :   Using  “KeyPath”

Given a URL which returns weather data in the following form:

{
    "data": {
        "location": "Toronto, Canada",    
        "three_day_forecast": [
            { 
                "conditions": "Partly cloudy",
                "day" : "Monday",
                "temperature": 20 
            },
            { 
                "conditions": "Showers",
                "day" : "Tuesday",
                "temperature": 22 
            },
            { 
                "conditions": "Sunny",
                "day" : "Wednesday",
                "temperature": 28 
            }
        ]
    }
}

The keyPath variable is used to drill down into a JSON response and only map the data found at that keyPath. It supports nested values such as data.location to drill down several levels in a JSON response.

we are taking data from key “data

let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/2ee8f34d21e8febfdefb2b3a403f18a43818d70a/sample_keypath_json"

Alamofire.request(URL).responseObject(keyPath: "data") { (response: DataResponse<WeatherResponse>) in    
    let weatherResponse = response.result.value
    print(weatherResponse?.location)
    
    if let threeDayForecast = weatherResponse?.threeDayForecast {
        for forecast in threeDayForecast {
            print(forecast.day)
            print(forecast.temperature)           
        }
    }
}

Example 3 – Easy Mapping of Nested Objects

AlamofireObjectMapper supports dot notation within keys for easy mapping of nested objects. Given the following JSON String:

"distance" : {
     "text" : "102 ft",
     "value" : 31
}

You can access the nested objects as follows:

func mapping(map: Map) {
    distance <- map["distance.value"]
}

Example 4 – Array Responses

For example, if your endpoint returns the following:

[
    { 
        "conditions": "Partly cloudy",
        "day" : "Monday",
        "temperature": 20 
    },
    { 
        "conditions": "Showers",
        "day" : "Tuesday",
        "temperature": 22 
    },
    { 
        "conditions": "Sunny",
        "day" : "Wednesday",
        "temperature": 28 
    }
]

You can request and map it as follows:

let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/f583be1121dbc5e9b0381b3017718a70c31054f7/sample_array_json"
Alamofire.request(URL).responseArray { (response: DataResponse<[Forecast]>) in

    let forecastArray = response.result.value
    
    if let forecastArray = forecastArray {
        for forecast in forecastArray {
            print(forecast.day)
            print(forecast.temperature)           
        }
    }
}

githubDownloadButton.png You can download source code

240_F_77959340_hWLiOY93juohUoXqjKzqPB79552nw8XU

Hope you find this blog useful. Please feel free to contact with me in case you have any query, suggestions.  You can comment, like and follow posts.

You can request any topic related to Swift and iOS development.

Advertisements