2017年1月3日火曜日

jsonのdataをswift2で解析する

取得するデータの構造は
responseData:
  feed:
    value
       feeUrl : "value"
       ...  // *** 以下"キー:value"のメンバが続く
       entries:  // *** ここがおめあて
          value配列
             ...

とした場合、以下コードで最終亭なentriesキーのvalue配列が取得できました。
var dict:NSDictionary
dict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
//get responseData, feed, entries
let responseData = dict["responseData"] as! NSDictionary  // dictからresponseDataキーを探す
let feed = responseData["feed"] as! NSDictionary       // responseData からfeedキーを探す
let entries = feed["entries"] as! NSArray           // feedからentriesを探す..."entries"が配列として格納

entriesの配列の各titleを表示させる場合は以下になります。
//extract entries
// print(entries.count)
var titles:String = ""
for entry in entries {
 // print(entry["title"])
 let title:String = entry["title"] as! String
   titles += title + ":"
 }
 // print(titles)
 dispatch_async(dispatch_get_main_queue()){
  self.jsonTextView.text = titles
 }

0 件のコメント:

コメントを投稿