JSONレスポンスは下になります。
JSON
1{ 2 "info": { 3 "photo_num": ###, 4 "photo": [ 5 { 6 "photo_id": ###, 7 "user_id": ###, 8 "album_id": ###, 9 "photo_title": "タイトル", 10 "favorite_num": ###, 11 "comment_num": ###, 12 "view_num": ###, 13 "copyright": "normal/creativecommons", 14 "copyright_commercial": "yes/no" 15 "copyright_modifications": "yes/no/share" 16 "original_height": ##, 17 "original_width": ###, 18 "geo": { 19 "latitude": ###, 20 "longitude": ### 21 }, 22 "date": "YYYY-MM-DD", 23 "regist_time": "YYYY-MM-DDThh:mm:ss+09:00", 24 "url": "URL", 25 "image_url": "URL", 26 "original_image_url": "URL", 27 "thumbnail_image_url": "URL", 28 "large_tag": "<a href=\"...\">...</a>", 29 "medium_tag": "<a href=\"...\">...</a>" 30 }, 31 ... 32 ] 33 } 34}
上の中にある"image_url"を取り出したく下のようにコードを記載しました
Swift
1 Alamofire.request(url, method: .get, parameters: params, encoding: URLEncoding.default, headers: nil).responseData { (dataResponse) in 2 3 if let err = dataResponse.error{ 4 print("failed to contact photos", err) 5 return 6 } 7 8 guard let data = dataResponse.data else {return} 9 10 do{ 11 let searchResult = try JSONDecoder().decode(SearchResults.self, from: data) 12 self.photos = searchResult.info.photo! 13 self.collectionView.reloadData() 14 15 }catch let decodeErr{ 16 print("failed to decode:", decodeErr) 17 } 18 } 19 20 struct SearchResults: Decodable { 21 22 struct Photo: Decodable{ 23 let photo_num: Int? 24 let photo: [Photos]? 25 } 26 let info: Photo 27 } 28 29class Photos: Decodable{ 30 var image_url: String? 31 var original_image_url: String? 32} 33
しかし以下のようなエラーメッセージが出ます。
failed to decode: keyNotFound(CodingKeys(stringValue: "info", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "info", intValue: nil) ("info").", underlyingError: nil))
failed to decode: keyNotFound(CodingKeys(stringValue: "info", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "info", intValue: nil) ("info").", underlyingError: nil))
failed to decode: keyNotFound(CodingKeys(stringValue: "info", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "info", intValue: nil) ("info").", underlyingError: nil))
どなたか対処法をご教示いただけないでしょうか。