LoginSignup
11
9

More than 5 years have passed since last update.

Swift Unbox で JSON decode を簡単にまとめてみましょう。

Last updated at Posted at 2016-03-14

JSON を decode してくれるライブラリはたくさんありますが、最近知り合いに教えてもらって使い始めた、Unboxが最高に良すぎて惚れてしまったので、まとめておきます。

{
    "name" : "shun",
    "age" : 28,
    is_man: true,
    date: "2016-01-01"
}

このJSON の Model は、

struct User: Unboxable {
    let name: String
    let age: Int
    let isMan: Bool
    let date: NSDate?

    init(unboxer: Unboxer) {
        self.name = unboxer.unbox("name")
        self.age = unboxer.unbox("age")
        self.isMan = unboxed.unbox("is_man")

        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "YYYY-MM-dd"
        self.date = unboxer.unbox("date", formatter: dateFormatter) 
    }
}

となります。

実際に使うときは。

let user: User = try Unbox(dictionary)

簡単ですね!!
皆さんも是非使ってみてください〜

参考

11
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9