This post is part of my collection: Swift 2 – For Beginners.
JSON (JavaScript Object Notation) is a lightweight, human readable, open source, data-interchange format. In this example we will see how to serialize and deserialize objects to/from JSON using ObjectMapper in our iOS application.
For example, this would be the JSON representation of an object with two properties
name: string = “Juan Carlos”
age: Int = 29
ObjectMapper is an open source project to make JSON Object mapping written in Swift. It is available in github: ObjectMapper.
Reference ObjectMapper using CocoaPods
CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. We will use it to reference ObjectMapper in our project. (If would also be possible to add it as a submodule. Check the project in GitHub for more information)
To add ObjectMapper to our project we need to execute the following commands:
Install cocoapods
sudo gem install cocoapods
Create Podfile in our project root
touch Podfile
To reference ObjectMapper add this content to the PodFile
use_frameworks! pod 'ObjectMapper', '~> 1.0'
Select XCode path
sudo xcode-select --switch /Applications/Xcode.app
Add ObjectMapper repository
pod repo add ObjectMapper https://github.com/Hearst-DD/ObjectMapper.git
Install the project locally
pod install
Close XCode and open the created file *.xcworkspace. It contains our project and a reference to a new project called Pods. All our referenced projects will be contained in this new project.
Now we are ready to import and use ObjectMapper:
import ObjectMapper
Define our objects and implement the protocol “Mappeable”
To serialize and deserialize objects we must implement the protocol Mappeable.
// Mappeable source code public protocol Mappable { init?(_ map: Map) mutating func mapping(map: Map) }
Let’s write our User class, it will have two properties, name and age. The class will also implement the protocol Mappeable.
// Define our class and implement the Mappable protocol class User: Mappable { var name: String? var age: Int = 0 init(name: String, age: Int) { self.name = name self.age = age } // MARK: Mappable required init?(_ map: Map) { // subClasses must call the constructor of the base class // super.init(map) } func mapping(map: Map) { name <- map["name"] age <- map["age"] } }
Serialize and Deserialize objects
ObjectMapper is extremely easy to use:
// Object to be serialized to JSON let myUser = User(name: "Juan Carlos", age: 29) // Convert Object to JSON let serializedUser = Mapper().toJSONString(myUser) print(serializedUser) // Convert JSON to Object if let deserializedUser = Mapper<User>().map(serializedUser){ print(deserializedUser.name) } // Output: // Optional("{\"age\":29,\"name\":\"Juan Carlos\"}") // Optional("Juan Carlos")
You explained it really well.Thank you.
LikeLike