LoginSignup
juncreates
@juncreates

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

Swift JSONのキーがユーザーの入力値によって動的変化する場合のアクセス方法

{
 "dates": {
   "2020-08-04": {
     "countries": {
       "Japan": {
         "date": "2020-08-04",
         "id": "japan",
         "links": [1 item],
         "name": "Japan",
         "name_es": "Japón",
         "name_it": "Giappone",
         "today_new_confirmed": 417,
       },
     } 
}
}
} 

上記のJSON構造で"today_new_confirmed"の417 にアクセスしたいのですが、
"2020-08-04"と"Japan"はアクセスする日付と、ユーザーの入力値によって動的に変化します。

この場合、どうすればいいのでしょうか。
モデルを作ろうとするものの、キーの値が分からないため設定ができない状態です。

stackoverflowでも調べましたが、いまいちヒットせず、、、

よろしお願いいたします。

0

1Answer

Dictionary が使えます。

struct Country: Codable {
    var todayNewConfirmed: Int
}

struct DailyData: Codable {
    var countries: [String : Country]
}

struct Response: Codable {
    var dates: [String : DailyData]
}

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

let response = try! decoder.decode(Response.self, from: data)
response.dates["2020-08-04"]?.countries["Japan"]?.todayNewConfirmed
1

Your answer might help someone💌