はい。こんな感じでどうでしょう。
swift
1let jsonDict = response.result.value as! NSDictionary
2print(jsonDict)
3let id = jsonDict["id"] as! Int
4print(id)
5let name = jsonDict["name"] as! String
6print(name)
以下のように書くとどのような出力になりますか。
swift
1.responseJSON { response in
2 switch response.result {
3 // データを取り出す
4 case .Success(let value):
5 print(value)
6 // 失敗時エラー出力
7 case .Failure(let error):
8 print(error)
9 }
10}
また、requestUrl
を変更しても出力に違いが見られませんか。
requestUrl
をhttps://tepco-usage-api.appspot.com/latest.json
にすると、私の環境では以下のような出力になります。
json
1{
2 capacity = 4214;
3 "capacity_peak_period" = 17;
4 "capacity_updated" = "2012-12-24 08:30:00";
5 day = 25;
6 entryfor = "2015-12-24 16:00:00";
7 forecast = 0;
8 "forecast_peak_period" = 17;
9 "forecast_peak_updated" = "2012-12-24 08:30:00";
10 "forecast_peak_usage" = 3620;
11 hour = 1;
12 month = 12;
13 saving = 0;
14 usage = 2623;
15 "usage_updated" = "2015-12-24 17:05:06";
16 year = 2015;
17}
ご参考にしてください。
これで動くでしょう。
以下のAPIで動作を確認しました。
https://tepco-usage-api.appspot.com/latest.json
https://qiita.com/api/v2/items
SwiftyJSON
やArgo
のようなJSONパーサを利用したほうがきっと幸せになれるでしょう。
SwiftyJSON/SwiftyJSON
thoughtbot/Argo
swift
1.responseJSON { response in
2 switch response.result {
3 // データを取り出す
4 case .Success(let value):
5 // print(value)
6 let dataArray = NSMutableArray()
7 var dict = NSDictionary()
8 // レスポンスのデータ型を確認
9 if value is NSDictionary {
10 // print("value is Dictionary type.")
11
12 dict = value as! NSDictionary
13 dataArray.addObject(dict)
14
15 } else if value is NSArray {
16 // print("value is Array type.")
17
18 let count = value.count
19 for(var i = 0; i < count; ++i) {
20 dict = value[i] as! NSDictionary
21 dataArray.addObject(dict)
22 }
23 }
24 print("データ数: \(dataArray.count)")
25 print(dataArray[0])
26 // print(dataArray[0]["id"] as! Int)
27 // 失敗時エラー出力
28 case .Failure(let error):
29 print(error)
30 }
31}
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/12/24 11:34
2015/12/26 04:43