統計情報(30日間)


最新情報をツイート


人気の投稿

#swift JSONライブラリ

このエントリーをはてなブックマークに追加

こんなJSONがあったとする。

[
  {
    ......
    "text": "just another test",
    ......
    "user": {
      "name": "OAuth Dancer",
           :

nameを取り出すと
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{
                //Finally We Got The Name

            }
        }
    }
}
とか
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
}
とか

どう見てもイケてない。

このライブラリを使うと
let json = JSONValue(dataFromNetworking)
if let userName = json[0]["user"]["name"].string{
  //Now you got your value
}
と書ける。
そのほか
let json = JSONValue(jsonObject)
switch json["user_id"]{
case .JString(let stringValue):
    let id = stringValue.toInt()
case .JNumber(let doubleValue):
    let id = Int(doubleValue)
default:
    println("ooops!!! JSON Data is Unexpected or Broken")

いいね。



Leave a Reply