タイトルの通りです。
collectionViewControllerでAPIで取得したテキストを表示したく
Codable
を使用してAPIで取得したJsonデータを整形しています。
その中のネストされているデータを全て取得したい(for文のイメージ)のですが、どのようにコードを描けばよろしいでしょうかご教授いただけると幸いです。
下記のように書いてみましたがtag[0].name
だと一つしか取得できないのでtag
内のname
を全て取得できるようにしたいです。
GetJsonDataCode
1store![indexPath.row].tag[0].name
Codable
1truct Store : Codable { 2 let id : Int 3 let name : String 4 let location : String 5 let price : String 6 let open_time : String 7 let closed_day : String 8 let categories : [categories] 9 let tags : [tags] 10 11 struct categories : Codable { 12 let id : Int 13 let name : String 14 } 15 16 struct tags: Codable { 17 let id : Int 18 let name : String 19 } 20} 21
JsonDecode
1 2 let url = URL(string: "http://localhost:8000/store/api?store_id=" + store_id) 3 let request = URLRequest(url: url!) 4 let session = URLSession.shared 5 6 let encoder: JSONEncoder = JSONEncoder() 7 encoder.dateEncodingStrategy = .iso8601 8 encoder.outputFormatting = .prettyPrinted 9 10 session.dataTask(with: request){(data, response, error)in if error == nil, 11 let data = data, 12 let response = response as? HTTPURLResponse{ 13 14 let decoder: JSONDecoder = JSONDecoder() 15 decoder.dateDecodingStrategy = .iso8601 16 do { 17 18 let json = try decoder.decode(Store.self, from: data) 19 20 // for store in (json.stores){ 21 // for photo in (store.photos){ 22 // print(photo.path as Any) 23 // } 24 // } 25 26 27 self.store = [json] 28 29 DispatchQueue.main.async { 30 self.nameLabel.text = json.name 31 self.locationLabel.text = json.location 32 } 33 34 } catch { 35 print("error:", error.localizedDescription) 36 37 } 38 39 } 40 41 }.resume()
回答1件
あなたの回答
tips
プレビュー