この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
SwiftでJSONを扱う
今回は楽天ブックス書籍検索APIの取得結果を例として利用します。
JSONの内容は下記の通りです。
{
"count": 22,
"page": 1,
"first": 1,
"last": 22,
"hits": 22,
"carrier": 0,
"pageCount": 1,
"Items": [
{
"Item": {
"title": "ニセコイ 15",
"titleKana": "ニセコイ",
"subTitle": "",
"subTitleKana": "",
"seriesName": "ジャンプコミックス",
"seriesNameKana": "ジヤンプ コミツクス",
"contents": "",
"author": "古味直志",
"authorKana": "コミナオシ",
"publisherName": "集英社",
"size": "コミック",
"isbn": "9784088802220",
"itemCaption": "",
"salesDate": "2014年12月04日",
"itemPrice": 432,
"listPrice": 0,
"discountRate": 0,
"discountPrice": 0,
"itemUrl": "http://books.rakuten.co.jp/rb/12985224/",
"affiliateUrl": "",
"smallImageUrl": "http://thumbnail.image.rakuten.co.jp/@0_mall/book/cabinet/noimage_01.gif?_ex=64x64",
"mediumImageUrl": "http://thumbnail.image.rakuten.co.jp/@0_mall/book/cabinet/noimage_01.gif?_ex=120x120",
"largeImageUrl": "http://thumbnail.image.rakuten.co.jp/@0_mall/book/cabinet/noimage_01.gif?_ex=200x200",
"chirayomiUrl": "",
"availability": "5",
"postageFlag": 0,
"limitedFlag": 0,
"reviewCount": 0,
"reviewAverage": "0.0",
"booksGenreId": "001001001008"
}
},
・・・
],
"GenreInformation": []
}
Itemsに含まれる1件目の「title」を取り出すには、
下記内容のコードになります。
let json:NSDictionary = NSJSONSerialization.JSONObjectWithData(data,
options: NSJSONReadingOptions.AllowFragments, error: nil) as NSDictionary
if let itemsArray = json["Items"] as? NSArray {
if let aItem = itemsArray[0] as? NSDictionary {
if let item = aItem["Item"] as? NSDictionary {
if let title = item["title"] as? NSString {
println(title)
}
}
}
}
めんどい…
SwiftyJSON
JSONを簡単に扱う為のライブラリ SwiftyJSONを紹介します。
https://github.com/SwiftyJSON/SwiftyJSON
先ほどのコードにSwiftyJSONを適用します。
「SwiftyJSON.swift」をプロジェクト内に配置し、下記コードに置き換えるだけです。
let json = JSON(data: data)
if let title = json["Items"][0]["Item"]["title"].string {
println(title)
}
簡単!!
細かい使い方を見ていきます。
Initialization
let json = JSON(data: data)
Subscript
// Dictionary
let name = json["name"].stringValue
// Array
let name = json[0].double
Loop
// Dictionary
let json = JSON(data: data)
for (key: String, subJson: JSON) in json {
// keyにはJSONのキーが設定されている。
println(key)
}
// Array
let json = JSON(data: data)
for (index: String, subJson: JSON) in json["Items"] {
// 0,1,2,3...
println(index)
}
Error
// index out-of-bounds
let json = JSON(data: data)
if let title = json["Items"][999]["Item"]["title"].string {
} else {
println(json["Items"][999]["Item"]["title"].error!) // Array[999] is out of bounds
}
// does not exist
let json = JSON(data: data)
if let title = json["Test"].string {
} else {
println(json["Test"].error!) // Dictionary["Test"] does not exist
}
Optional 型のgetter
// NSNumber
if let id = json["count"].number {
} else {
// errorの処理
}
// String
if let id = json["Items"][0]["Item"]["title"].string {
} else {
// errorの処理
}
非 Optional 型のgetter
// nilの場合、0が返却される。
let id: Int = json["count"].intValue
// nilの場合、空文字が返却される。
let name: String = json["Items"][0]["Item"]["title"].stringValue
// nilの場合、[]が返却される。
let list: Array<JSON> = json["Items"].arrayValue
// nilの場合、[:]が返却される。
let user: Dictionary<String, JSON> = json["Items"][0]["Item"].dictionaryValue
Raw object
let jsonObject: AnyObject = json.object
if let jsonObject: AnyObject = json.rawValue
// NSData
if let data = json.rawData() {
}
// String
if let string = json.rawString() {
}
まとめ
現在のiOSアプリ開発では、JSONを扱う機会がとても多いと思います。
SwiftyJSONを使って、JSONを簡単に扱いましょう!
参考
https://github.com/SwiftyJSON/SwiftyJSON
http://qiita.com/yukihamada/items/9b0067f905418105a2c6
http://qiita.com/g08m11/items/c3746cbdbdb4c7b71607
https://dev.classmethod.jp/references/ios-8-xcode-6-swift-api-json/