144
141

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swiftで面倒なJSONの取り扱いを10倍便利にするSwiftyJSON

Last updated at Posted at 2014-07-04

SwiftyJSON
https://github.com/lingoer/SwiftyJSON

上記を読んでしまえば一瞬なんですが、一応使い方をこちらにもそのまま書いておきます。

#JSONの取り扱いって面倒ですよね?

[
  {
    ......
    "text": "just another test",
    ......
    "user": {
      "name": "OAuth Dancer",
      "favourites_count": 7,
      "entities": {
        "url": {
          "urls": [
            {
              "expanded_url": null,
              "url": "http://bit.ly/oauth-dancer",
              "indices": [
                0,
                26
              ],
              "display_url": null
            }
          ]
        }
      ......
    },
    "in_reply_to_screen_name": null,
  },
  ......]

こんなデータがあったとします。

データの取り出しはこんな感じ

let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(dataFromTwitter, options: NSJSONReadingOptions.MutableContainers, error: nil)
if let statusesArray = jsonObject as? NSArray{
    if let aStatus = statusesArray[0] as? NSDictionary{
        if let user = aStatus["user"] as? NSDictionary{
            if let userName = user["name"] as? NSDictionary{
                //やっと取り出せました。

            }
        }
    }
}

面倒ですよね。。
下記のような方法でも汚い。

let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(dataFromTwitter, options: NSJSONReadingOptions.MutableContainers, error: nil)
if let userName = (((jsonObject as? NSArray)?[0] as? NSDictionary)?["user"] as? NSDictionary)?["name"]{
  //What A disaster above
}

#そこでSwiftyJSONの登場

##セットアップ
https://github.com/lingoer/SwiftyJSON
まだswiftはpodに対応していないらしいので上記からzipをダウンロード&解答してSwiftyJSON.swiftをダウンロードしてプロジェクトに投げ込んで設定完了

この辺から見てください
cocoapodsセットアップからSwiftyJSON動作確認まで

##使い方

var url = "http://maps.googleapis.com/maps/api/directions/json?origin=Boston,MA&destination=Concord,MA&sensor=false"
var reqest = NSURLRequest(URL: NSURL(string: url))

NSURLConnection.sendAsynchronousRequest(reqest,queue: NSOperationQueue.mainQueue(),completionHandler:{
    (res: NSURLResponse!, data: NSData!, error: NSError!) in
        let json = JSONValue(data)
        if let distance = json["routes"][0]["legs"][0]["distance"]["text"].string{
            println(distance)
        }
})

簡単ですね。

144
141
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
144
141

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?