質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

1739閲覧

swiftでのjsonデータの扱い方

jiuiuoiui

総合スコア24

iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2016/11/16 06:00

編集2016/11/16 07:52

以下のURLのjsonデータから、各キャラクターのidとtitleを取り出したいのですが、どのようにすればいいのかわかりません。
リンク内容
以下のようなコードを書いてみましたが、データの解析のところでかなり間違いがあると思います..

Swift

1import UIKit 2 3class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,URLSessionDelegate { 4 5 var characters: [String] = [] 6 var explains: [String] = [] 7 8 @IBOutlet weak var myTable: UITableView! 9 10 11 override func viewDidLoad() { 12 super.viewDidLoad() 13 setuptableview() 14 // Do any additional setup after loading the view, typically from a nib. 15 } 16 17 override func didReceiveMemoryWarning() { 18 super.didReceiveMemoryWarning() 19 // Dispose of any resources that can be recreated. 20 } 21 22 func setuptableview(){ 23 let url: NSURL = NSURL(string: "https://global.api.pvp.net/api/lol/static-data/jp/v1.2/champion?api_key=RGAPI-40046844-78a7-43b4-81af-caedf4a701d1")! 24 let configuration: URLSessionConfiguration = URLSessionConfiguration.default 25 let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) 26 27 let task: URLSessionDataTask = session.dataTask(with: url as URL, completionHandler: {(data, response, err) -> Void in 28 if data != nil{ 29 let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) 30 print(str!) 31 32 do{ 33 let json: NSDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary 34 let champions = json["data"] as! [[String:AnyObject]] 35 36 for championdates in champions { 37 self.characters.append(championdates["key"] as! String) 38 self.explains.append(championdates["title"] as! String) 39 } 40 41 }catch{ 42 print("error") 43 print(error) 44 } 45 } 46 }) 47 task.resume() 48 } 49 50 func tableView(_ table: UITableView, numberOfRowsInSection section: Int) -> Int { 51 return characters.count 52 } 53 54 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 55 print("test") 56 // tableCell の ID で UITableViewCell のインスタンスを生成 57 let cell = myTable.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) 58 59 // Tag番号 1 で UIImageView インスタンスの生成 60 let imageView = myTable.viewWithTag(1) as! UIImageView 61 let url = NSURL(string:"http://ddragon.leagueoflegends.com/cdn/6.22.1/img/champion/\(characters[indexPath.row]).png") 62 let req = NSURLRequest(url: url! as URL,cachePolicy: .returnCacheDataElseLoad,timeoutInterval: 5*60) 63 let conf = URLSessionConfiguration.default; 64 let session = URLSession(configuration: conf, delegate: nil, delegateQueue: OperationQueue.main) 65 66 session.dataTask(with: req as URLRequest, completionHandler: 67 { (data, resp, err) in 68 if((err) == nil){ //Success 69 let image = UIImage(data:data!) 70 imageView.image = image 71 }else{ //Error 72 print("AsyncImageView:Error \(err?.localizedDescription)"); 73 } 74 self.myTable.reloadData() 75 }).resume(); 76 77 78 79 // Tag番号 2 で UILabel インスタンスの生成 80 let label1 = myTable.viewWithTag(2) as! UILabel 81 label1.text = "\(characters[indexPath.row])" 82 // Tag番号 3 で UILabel インスタンスの生成 83 let label2 = myTable.viewWithTag(3) as! UILabel 84 label2.text = "\(explains[indexPath.row])" 85 86 return cell 87 88 } 89} 90

回答お願いします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

dataはArrayじゃなくてDictionaryです。
名前(name?)がキーになっていて、データ本体が値になっています。

特定の人にアクセスする場合はキーを指定すればいいのですが、今回の場合はキーを指定できませんので、.1で直接データにアクセスします。(.0にはキーが入っていいます)

swift

1let champions = json["data"] as! [String:[String:AnyObject]] //※Dictionary 2 3for championdates in champions { 4 print("[\(championdates.0)]") //これはキー 5 self.characters.append(championdates.1["key"] as! String) //データ本体の"key" 6 self.explains.append(championdates.1["title"] as! String) //データ本体の"title" 7}

投稿2016/11/16 07:05

fuzzball

総合スコア16731

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

jiuiuoiui

2016/11/16 07:52

回答ありがとうございます。jsonデータが記述されているURLが間違っていたので、再度記述しました。
fuzzball

2016/11/16 08:28

コードのURLを使ったので問題ないと思いますが、ダメだったのでしょうか?
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問