0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】CodableでネストしたJSONを変換する

Last updated at Posted at 2021-08-29

はじめに

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は一見難しいように見えましたが、見た目通りに構造体を用意してあげることで簡単にデコードすることができました。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?