swift-json
を使ってみたのでそのメモです。
swift-jsonとは
あの有名な小飼弾さんの作ったSwiftライブラリで、JSONの扱いを楽にしてくれます。
400スター以上付いている人気ライブラリです。
swift-jsonのインストール
swift-json
はCocoaPodsに対応していないようなので、ファイルを直接プロジェクトに追加します。
とは言っても1ファイルだけなのでそこまで手間ではありません。
下URLのjson.swift
をプロジェクトに追加します。
swift-json/json at master · dankogai/swift-json · GitHub
swift-jsonを使ってみる
swift-json
は下のように使います。
let dic = [ "string": "str", "bool": true, "int": 1, "array": [1, 2, 3], "dic": ["A":"B"] ] let json = JSON(dic) print(json["string"].asString) // → Optional(str) print(json["bool"].asBool) // → Optional(true)
当然ですが!
を付けると非Optionalな値を取れます。
let json = JSON(dic) print(json["string"].asString!) // → str
入れ子も下のように取得できます。
let json = JSON(dic) json["dic"]["A"].asString // → Optional(str)
型が違う場合はnilになります。
let json = JSON(dic) println(json["string"].asBool) // → nil
存在しないキーで取得しようとするとJSONErrorDomain
というエラーが出力されます。(アプリのクラッシュはしないです)
let json = JSON(dic) println(json["nothing"]) // → Error Domain=JSONErrorDomain Code=404 "["nothing"] not found"
エラーの場合にasError
でNSError
を取得する事もできます。
let json = JSON(dic) println(json["nothing"].asError) // → Error Domain=JSONErrorDomain Code=404 "["nothing"] not found"
試してはないのですが、他にも型を取るtype
やディクショナリーか判定するisDictionary
などの便利メソッドもあるようです。
シンプルなライブラリですが多機能で非常に便利そうです。