現在リクエストを送り、レスポンスをCodableを使用して任意の形に整えたいと思っています。
そこでCodableを使用してニニの形にしようと思ったのですが、コードが動きません。
実行すると地震で設定した下記のエラー文が出力されます
The data couldn’t be read because it isn’t in the correct format.
このエラー文は型が正しくないから読み込むことができないという意味ですが、こちらはJsonStringで
任意の取得したい値だけしか書いていないからでしょうか。
どなたか教えてくださいませうと幸いです。
API response
Json
1{ 2"id": 1, 3 "name": "誕生日", 4 "created_at": "2018-08-09 10:00:58", 5 "updated_at": "2018-08-09 10:00:58", 6 "stores": [ 7 { 8 "id": 1, 9 "name": "Pink Cafe Tokyo", 10 "location": "東京", 11 "price": "1000~3000", 12 "open_time": "10:00-14:00", 13 "closed_day": "月曜日", 14 "created_at": "2018-08-09 10:03:52", 15 "updated_at": "2018-08-09 10:03:52", 16 "pivot": { 17 "store_id": 1, 18 "category_id": 1 19 }, 20 "tags": [ 21 { 22 "id": 1, 23 "name": "スイーツ", 24 "created_at": "2018-08-09 10:00:58", 25 "updated_at": "2018-08-09 10:00:58", 26 "pivot": { 27 "tag_id": 1, 28 "store_id": 1 29 } 30 }, 31 { 32 "id": 13, 33 "name": "ピンクカフェ", 34 "created_at": "2018-08-09 10:00:58", 35 "updated_at": "2018-08-09 10:00:58", 36 "pivot": { 37 "tag_id": 1, 38 "store_id": 13 39 } 40 }, 41 { 42 "id": 14, 43 "name": "コンセプトカフェ", 44 "created_at": "2018-08-09 10:00:58", 45 "updated_at": "2018-08-09 10:00:58", 46 "pivot": { 47 "tag_id": 1, 48 "store_id": 14 49 } 50 } 51 ], 52 "photos": [ 53 { 54 "id": 1, 55 "store_id": 1, 56 "path": "photos/Pink Cafe Tokyo_0.jpeg", 57 "created_at": "2018-08-09 10:03:52", 58 "updated_at": "2018-08-09 10:03:52" 59 } 60 ] 61 } 62 ] 63}
JsonString
swift
1struct categories : Codable { 2 let id : Int 3 let name : String 4 let stores : stores 5 6 struct stores : Codable { 7 let id : Int 8 let name : String 9 let location : String 10 let price : String 11 let open_time : String 12 let closed_day : String 13 let photos : photos 14 let tags : tags 15 16 struct photos:Codable { 17 let id : Int 18 let path : String 19 } 20 21 struct tags:Codable { 22 let id : Int 23 let name : String 24 } 25 } 26}
HomeViewController
swift
1@IBAction func search_btn(_ sender: Any){ 2 let url = URL(string: "http://127.0.0.1:8000/search/api/category?category_id=1") 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: categories = try decoder.decode(categories.self, from: data) 19 print(json) 20 21 } catch { 22 print("error:", error.localizedDescription) 23 } 24 25 } 26 }.resume() 27 } 28
回答1件
あなたの回答
tips
プレビュー