Life is Really Short, Have Your Life!!

ござ先輩の主に技術的なメモ

JSON⇔オブジェクトの変換はObjectMapperが簡単で好き

3日ぐらい前にSwift2.0対応をしてくれました。ありがてぇありがてぇ。

github.com

Mappableというプロトコルを実装するだけで使えるようになりますし、Realmのオブジェクトもシリアライズすることが出来ます。

//User.swift
import ObjectMapper

class User : Mappable {
    var id:Int? = 0
    var name:String? = ""
    
    required init?(_ map: Map){
        mapping(map)
    }
    
    func mapping(map: Map) {
        name <- map["name"]
        id <- map["id"]
    }
}

こんな感じで使います。

import ObjectMapper

//Single
Mapper<User>().map("{\"id\":1,\"name\":\"Hello World\"}")
//Array
Mapper<User>().mapArray("[{\"id\":1,\"name\":\"Hello World\"},{\"id\":2,\"name\":\"Foo bar\"}]")

Alamofireのrequestメソッドの拡張で、レスポンスをObjectMapperのMappableをインプリしてるクラスのオブジェクトにするラッパーもあります。

github.com

僕個人は、SwiftyJSON使ったことがない。これらで十二分なんで。