objectmapper


About ObjectMapper

ObjectMapper is an open-source framework for Objective-C and Swift that simplifies the process of converting objects between different representations, such as JSON and native Swift/Obj-C objects. It provides a simple and convenient way to map JSON data to model objects (and vice versa) without the need for manual parsing or boilerplate code.

With ObjectMapper, you can easily serialize/deserialize models to JSON, create model objects from JSON dictionaries, perform deep JSON mapping, convert between CamelCase and snake_case, handle nested objects, and much more.

This documentation page provides a comprehensive guide on how to use ObjectMapper in your projects, including installation instructions, basic usage, advanced features, and best practices. Whether you are a beginner or an experienced developer, this guide will help you leverage the power of ObjectMapper in your iOS/MacOS projects.

Table of Contents

Installation

To start using ObjectMapper in your project, follow these steps:

  • Step 1: Add ObjectMapper to your project using CocoaPods or Swift Package Manager
  • Step 2: Import the ObjectMapper module in your Swift or Obj-C files
  • Step 3: Start using ObjectMapper in your project

Basic Usage

Mapping between objects and JSON data is effortless with ObjectMapper. Here’s a basic example:

1. Define your model class:

class Person: Mappable {
    var name: String?
    var age: Int?
    
    required init?(map: Map) {}
    
    func mapping(map: Map) {
        name <- map["name"]
        age <- map["age"]
    }
}

2. Deserialize JSON into a model object:

let jsonString = "{\"name\":\"John Doe\",\"age\":30}"
if let person = Mapper<Person>().map(jsonString) {
    print(person.name)
    print(person.age)
}

This code creates a `Person` object and assigns the values from the JSON string to the corresponding properties (`name` and `age`).

Mapping Options

ObjectMapper provides various mapping options to customize the mapping behavior. Some of the commonly used options are:

  • Converting data types
  • Mapping complex objects
  • Ignoring properties
  • Setting default values
  • Transforming values

Nested Objects

Mapping nested objects is straightforward with ObjectMapper. Consider the following example:

class Address: Mappable {
    var street: String?
    var city: String?
    
    required init?(map: Map) {}
    
    func mapping(map: Map) {
        street <- map["street"]
        city <- map["city"]
    }
}

class Person: Mappable {
    var name: String?
    var age: Int?
    var address: Address?
    
    required init?(map: Map) {}
    
    func mapping(map: Map) {
        name <- map["name"]
        age <- map["age"]
        address <- map["address"]
    }
}

Array Mapping

ObjectMapper supports mapping arrays of objects, which is useful when dealing with JSON arrays. Here’s an example:

let jsonArray = "[{\"name\":\"John Doe\",\"age\":30}, {\"name\":\"Jane Smith\",\"age\":25}]"
if let people = Mapper<Person>().mapArray(jsonArray) {
    for person in people {
        print(person.name)
        print(person.age)
    }
}

This code maps an array of JSON objects to an array of `Person` objects.

Custom Transformations

ObjectMapper allows you to define custom transformations for your model properties. You can transform data types, format dates, or apply any other custom logic during mapping. Here’s an example:

class Event: Mappable {
    var name: String?
    var date: Date?
    
    required init?(map: Map) {}
    
    func mapping(map: Map) {
        name <- map["name"]
        date <- (map["date"], CustomDateTransform())
    }
}

struct CustomDateTransform: TransformType {
    typealias Object = Date
    typealias JSON = String
    
    init() {}
    
    func transformFromJSON(_ value: Any?) -> Object? {
        if let dateString = value as? String {
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd"
            return formatter.date(from: dateString)
        }
        return nil
    }
    
    func transformToJSON(_ value: Object?) -> JSON? {
        if let date = value {
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd"
            return formatter.string(from: date)
        }
        return nil
    }
}

Key Paths

ObjectMapper supports mapping JSON key paths to nested properties. This feature is useful when working with complex JSON structures or when the property names in your model class don’t match the JSON keys. Here’s an example:

class User: Mappable {
    var name: String?
    var email: String?
    var address: String?
    
    required init?(map: Map) {}
    
    func mapping(map: Map) {
        name <- map["user.name"]
        email <- map["user.email"]
        address <- map["user.details.address"]
    }
}

Best Practices

When using ObjectMapper, consider the following best practices:

  • Define model classes conforming to the `Mappable` protocol
  • Keep your model classes clean and focused on data representation
  • Use naming conventions compatible with your JSON keys
  • Make use of mapping options for handling specific cases
  • Ensure consistent data type mapping

By following these best practices, you can maintain clean and efficient code while taking full advantage of ObjectMapper’s capabilities.