はじめに
HotPepperBeautyAPIから返ってきたJSONをDecodeしようとした際に少し詰まったので備忘録として書きます。
やりたいこと
下記のJSONをDecodeし、access
のデータを使用したい。
{
"results": {
"api_version": "1.26",
"results_available": 27716,
"results_returned": "10",
"results_start": 1,
"shop": [
{
"access": "渋谷駅ハチ公口徒歩3分バスケットボールストリート(渋谷センター街)通りの1階 ウエンディーズ白馬ビル4階",
"address": "東京都渋谷区宇田川町26-11 白馬ビル4階",
"band": "不可",
"barrier_free": "なし :心地よい時間をご提供できるよう随時サポートさせて頂きます。",
"budget": {
"average": "通常平均:3280円/宴会平均:3280円/ランチ平均:3280円",
"code": "B002",
"name": "2001~3000円"
},
...
現状
access
を使用したく、以下の構造体を用意。
struct Shop: Codable {
let access: String
enum CodingKeys: String, CodingKey {
case access = "access"
}
}
エラー内容
「キーに関連付けられた値がありません」とのエラー。タイポミス等を疑い諸々チェックしたのですが、解決せず。
keyNotFound(CodingKeys(stringValue: "access", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"access\", intValue: nil) (\"access\").", underlyingError: nil))
原因・解決方法
構造体をresultsから用意していなかったこと
が原因だった。なので、以下のようにresultsから構造体を作成すると無事にDecodeすることができた。
struct Results: Codable {
let results: ResultsData
}
struct ResultsData: Codable {
let shop: [Shop]
}
struct Shop: Codable {
let access: String
enum CodingKeys: String, CodingKey {
case access = "access"
}
}
最後に
ネストしたJSONは一見難しいように見えましたが、見た目通りに構造体を用意してあげることで簡単にデコードすることができました。