前提・実現したいこと
SwiftでぐるなびAPIを利用しています。
https://api.gnavi.co.jp/api/manual/restsearch/
ぐるなびAPIからJSONを利用してデータを取得していますが、下記エラーが出ます。
The data couldn’t be read because it isn’t in the correct format.
Jsonで取得したデータが空の場合の挙動についてまだ理解していないため定かではありませんが、ぐるなびAPIのbudgetの値がある場合はINTとして取得しており、値が空の場合" "になっていることから、Stringで取得してしまっているように見えます。
JSON
1 { 2 "@attributes": { 3 "api_version": "v3" 4 }, 5 "total_hit_count": 20832, 6 "hit_per_page": 10, 7 "page_offset": 1, 8 "rest": [ 9 { 10 "@attributes": { 11 "order": 0 12 }, 13 "id": "", 14 "update_date": "", 15 "name": "", 16 "name_kana": "", 17 "latitude": "", 18 "longitude": "", 19 "category": "", 20 "url": "", 21 "url_mobile": "", 22 "coupon_url": { 23 "pc": "", 24 "mobile": "" 25 }, 26 "image_url": { 27 "shop_image1": "", 28 "shop_image2": "", 29 "qrcode": "" 30 }, 31 "address": "", 32 "tel": "", 33 "tel_sub": "", 34 "fax": "", 35 "opentime": "", 36 "holiday": "", 37 "access": { 38 "line": "", 39 "station": "", 40 "station_exit": "", 41 "walk": "", 42 "note": "" 43 }, 44 "parking_lots": "", 45 "pr": { 46 "pr_short": "", 47 "pr_long": "" 48 }, 49 "code": { 50 "areacode": "", 51 "areaname": "", 52 "prefcode": "", 53 "prefname": "", 54 "areacode_s": "", 55 "areaname_s": "", 56 "category_code_l": [ 57 "", 58 "" 59 ], 60 "category_name_l": [ 61 "", 62 "" 63 ], 64 "category_code_s": [ 65 "", 66 "" 67 ], 68 "category_name_s": [ 69 "", 70 "" 71 ] 72 }, 73 "budget": 3000, //値がない場合は、"budget": "", 74 "party": 4000, 75 "lunch": 980, 76 "credit_card": "", 77 "e_money": "", 78 "flags": { 79 "mobile_site": 1, 80 "mobile_coupon": 1, 81 "pc_coupon": 1 82 } 83 }, 84
Swift
1 // MARK: - REST 2 struct REST: Codable { 3 let id: String 4 let budget:Int 5 6 enum CodingKeys: String, CodingKey { 7 case id = "id" 8 case budget = "budget" 9 } 10 }
Stringで定義してしまうと、値があるときにINTとなってしまうためエラーで出てしまい、
Intで定義してしまうと、値がない時にStringとなってしまいエラーが出てしまうため、どうすれば良いかわからない状況です。
またコード自体の書き方に問題がある可能性もあるため、解決方法をご教授いただけば幸いです。
回答1件
あなたの回答
tips
プレビュー