1
1

More than 1 year has passed since last update.

【Swift】CodableをCamelCaseで定義する方法

Last updated at Posted at 2022-09-11

サンプルデータ

Twitterのusers/showを一部抜粋してサンプルデータにしました

sample.json
{
    "id": 121314463,
    "id_str": "121314463",
    "name": "サンプル",
    "screen_name": "sample",
    "location": "japan",
    "description": "sample"
}

方法1(CodingKeysを使う)

SampleModel
import Foundation

struct SampleModel: Codable {
    let id: Int
    let idStr, name, screenName, location, description: String

    enum CodingKeys: String, CodingKey {
        case id
        case idStr = "id_str"
        case name
        case screenName = "screen_name"
        case location
        case description
    }
}
let decoder = JSONDecoder()
let sampleModel = try decoder.decode(SampleModel.self, from: data)
print(sampleModel)

方法2(convertFromSnakeCaseを使う)

SampleModel
import Foundation

struct SampleModel: Codable {
    let id: Int
    let idStr, name, screenName, location, description: String
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let sampleModel = try decoder.decode(SampleModel.self, from: data)
print(sampleModel)

おわり

9月10日〜9月11日はiOSDCに行ってきました!!
めっちゃ楽しかったです!!
iOSDCでの学びについての記事も投稿できたらいいなと思ってます!

1
1
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
1
1