Skip to content

Instantly share code, notes, and snippets.

@gologo13
Last active August 29, 2015 14:20
Show Gist options
  • Save gologo13/9a444c68f2d8bdb620d3 to your computer and use it in GitHub Desktop.
Save gologo13/9a444c68f2d8bdb620d3 to your computer and use it in GitHub Desktop.
[Swift]ObjectMapperを使ったRealmモデルへのJSONマッピング(Mantleとの比較あり) ref: http://qiita.com/gologo13/items/713e3ffccaf77cc79dd4
public protocol Mappable {
init?(_ map: Map)
mutating func mapping(map: Map)
}
import Realm
import ObjectMapper
// DBモデルにRLMObjectを継承させる
class UserEntity : RLMObject {
dynamic var id = ""
dynamic var name = ""
// initializer で mapping(map: Map) を呼び出す
required convenience init?(_ map: Map) {
self.init()
mapping(map)
}
}
// MARK: - ObjectMapper
extension UserEntity : Mappable {
func mapping(map: Map) {
id <- map["Result.user.id"]
name <- map["Result.user.name"]
}
}
import ObjectMapper
// 入力はJSON文字列
let JSONString = "{\"Result\": {\"user\": {\"id\": \"12345\", \"name\": \"gologo13\"}}}"
// モデルの型を Generics の引数として、Mapper に渡します
let user = Mapper<UserEntity>().map(JSONString)
println(user)
// 出力:
// Optional(UserEntity {
// id = 12345;
// name = gologo13;
// })
- ```required convenience init?(_ map: Map)```を実装する
- ```required convenience``` が付いてないとコンパイルエラーになる
- ```func mapping(map: Map)``` メソッドを実装する
- ```mutating``` が付いたままだとコンパイルエラーになる
### 使用例
次にObjectMapperを使って、JSONデータからUserEntityを生成する例を示します。
```swift
import ObjectMapper
// 入力はJSON文字列
let JSONString = "{\"Result\": {\"user\": {\"id\": \"12345\", \"name\": \"gologo13\"}}}"
// モデルの型を Generics の引数として、Mapper に渡します
let user = Mapper<UserEntity>().map(JSONString)
println(user)
// 出力:
// Optional(UserEntity {
// id = 12345;
// name = gologo13;
// })
import ObjectMapper
// 入力は Dictionary
let JSONObject = ["Result": [
"user": [
"id": "12345",
"name": "gologo13"
]
]]
let user = Mapper<UserEntity>().map(JSONObject)
println(user)
// 出力:
// Optional(UserEntity {
// id = 12345;
// name = gologo13;
// })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment