ObjectMapper is a framework written in Swift that makes it easy for you to convert your Model objects (Classes and Structs) to and from JSON. ##Features:
- Mapping JSON to objects
- Mapping objects to JSON
- Nested Objects (stand alone, in Arrays or in Dictionaries)
- Custom transformations during mapping
- Struct support
##The Basics
To support mapping, a Class or Struct just needs to implement the Mappable
protocol. ObjectMapper uses the <=
operator to define how each member variable maps to and from JSON.
class User: Mappable {
var username: String?
var age: Int?
var weight: Double!
var arr: [AnyObject]?
var dict: [String : AnyObject] = [:]
var bestFriend: User? // Nested User object
var friends: [User]? // Array of Users
var birthday: NSDate?
required init(){}
// Mappable
func mapping(map: Map) {
username <= map["username"]
age <= map["age"]
weight <= map["weight"]
arr <= map["arr"]
dict <= map["dict"]
bestFriend <= map["best_friend"]
friends <= map["friends"]
birthday <= (map["birthday"], DateTransform())
}
}
struct Temperature: Mappable {
var celcius: Double?
var fahrenheit: Double?
init(){}
mutating func mapping(map: Map) {
celcius <= map["celcius"]
fahrenheit <= map["fahrenheit"]
}
}
Once your class implements Mappable, the Mapper class handles everything else for you:
Convert a JSON string to a model object:
let user = Mapper<User>().map(string: JSONString)
Convert a model object to a JSON string:
let JSONString = Mapper().toJSONString(user)
Object mapper can map classes composed of the following types:
- Int
- Bool
- Double
- Float
- String
- Array<AnyObject>
- Dictionary<String, AnyObject>
- Object<T: Mappable>
- Array<T: Mappable>
- Dictionary<String, T: Mappable>
- Optionals of all the above
- Implicitly Unwrapped Optionals of the above
##Easy Mapping of Nested Objects ObjectMapper 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"]
}
##Custom Transfoms
ObjectMapper also supports custom Transforms that convert values during the mapping process. To use a transform, simply create a tuple with map["field_name"]
and the transform of choice on the right side of the <=
operator:
birthday <= (map["birthday"], DateTransform())
The above transform will convert the JSON Int value to an NSDate when reading JSON and will convert the NSDate to an Int when converting objects to JSON.
You can easily create your own custom transforms by adopting and implementing the methods in the TransformType protocol:
public protocol TransformType {
typealias Object
typealias JSON
func transformFromJSON(value: AnyObject?) -> Object?
func transformToJSON(value: Object?) -> JSON?
}
##Installation ObjectMapper can be added to your project using Cocoapods 0.36 (beta) by adding the following line to your Podfile:
pod 'ObjectMapper', '~> 0.5'
If your using Carthage you can add a dependency on ObjectMapper by adding it to your Cartfile:
github "Hearst-DD/ObjectMapper" ~> 0.5
Otherwise, ObjectMapper can be added as a submodule:
- Add ObjectMapper as a submodule by opening the Terminal,
cd
-ing into your top-level project directory, and entering the commandgit submodule add https://github.com/Hearst-DD/ObjectMapper.git
- Open the
ObjectMapper
folder, and dragObjectMapper.xcodeproj
into the file navigator of your app project. - In Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the "Targets" heading in the sidebar.
- Ensure that the deployment target of ObjectMapper.framework matches that of the application target.
- In the tab bar at the top of that window, open the "Build Phases" panel.
- Expand the "Target Dependencies" group, and add
ObjectMapper.framework
. - Click on the
+
button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and addObjectMapper.framework
.