ä¸è¨ã®ããã«åºèæ å ±ã®ãã¼ãæ°åã«ãªã£ã¦ããJSONãã¼ã¿ããã·ãªã¢ã©ã¤ãºã§ãããï¼ã¨è³ªåãããåçãã¾ããã
{ "response": { "total_hit_count": 4, "0": { "shop_id": "6072772", "shop_name": "åºèA" }, "1": { "shop_id": "6072773", "shop_name": "åºèB" }, "2": { "shop_id": "6072774", "shop_name": "åºèC" }, "3": { "shop_id": "6072775", "shop_name": "åºèD" } } }
ããããã¨ãã¦åºèæ å ±ã¯é åã§æ¬²ããâ¦â¦ã¨æ°æã¡ãããã¾ãããããªã³APIãããã§ãã
解決編
CodingKeyãç¶æ¿ãããã¼ãªã¹ãã¯åºå®å¤(enum)ã§ããå¿ è¦ã¯ãªãã®ã§ãä¸è¨ã®ããã«å®ç¾©ãããã¨ãã§ãã¾ãã
struct CodingKeys: CodingKey { var stringValue: String init?(stringValue: String) { self.stringValue = stringValue } var intValue: Int? init?(intValue: Int) { return nil } }
ã³ã¼ãã®å ¨ä½ã¨ãã¦ã¯ä¸è¨ã®éãã§ãããã®APIã®æ°åé¨åãã©ãã¾ã§ä¼¸ã³ããä»æ§ãææ¡ã§ãã¦ããªãã®ã§ã仮㫠0 ã total_hit_count ã¾ã§ã®æ°åã®ãã¼ãããã¨æ³å®ãã¦ãã¾ãã
import Foundation struct Reviews: Decodable { let response: RakutenResponse } struct RakutenResponse: Decodable { let total_hit_count: Int let reviews: [Review] // MARK: - codable struct CodingKeys: CodingKey { var stringValue: String init?(stringValue: String) { self.stringValue = stringValue } var intValue: Int? init?(intValue: Int) { return nil } // åºå®ã§è¿ã£ã¦ãããã¼ static let total_hit_count = CodingKeys(stringValue: "total_hit_count")! } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) total_hit_count = try values.decode(Int.self, forKey: .total_hit_count) // NOTE: æ°åé¨åã®ä»æ§ãããããªãã®ã§ 0 ã hit_count ã¾ã§ãã¼ã¿ãåå¾ãã reviews = try (0 ..< total_hit_count) .map { (index) -> Review? in try values.decodeIfPresent(Review.self, forKey: CodingKeys(stringValue: "\(index)")!) } .compactMap { $0 } } } struct Store: Decodable { let shop_id: String let shop_name: String }