――As the title says, it is described as a memorandum. ――For camel case and snake case, please check with Google teacher. --Example: https://designsupply-web.com/media/developmentlab/4052/
When the API format is camel case when received by API. Simply put, if you can use it as it is.
import Foundation
struct Response: Codable {
///name
let firstName: String
///Last name
let lastName: String
}
///received data
var json = """
{
"firstName": "Yamada",
"lastName": "Taro"
}
"""
let data = json.data(using: .utf8)!
///Decoding process
let model = try! JSONDecoder().decode(Response.self, from: data)
print(model)
JSONDecoder
let jsonDecoder = JSONDecoder()
jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
Encode above.
However, this alone cannot be used automatically, so cut ʻenum, which is a derivative of
CodingKey`, in the receiving structure. It looks like the following
struct Response: Codable {
///name[first_name]
let firstName: String
///Last name[last_name]
let lastName: String
private enum CodingKeys: String, CodingKey {
case firstName
case lastName
}
}
With the following implementation, even if the API automatically returns in the snake case, it can be used in the camel case structure on the code side. Ah convenient (If you know it, it's not a big story, though)
import Foundation
struct Response: Codable {
///name[first_name]
let firstName: String
///Last name[last_name]
let lastName: String
private enum CodingKeys: String, CodingKey {
case firstName
case lastName
}
}
///received data
var json = """
{
"first_name": "Yamada",
"last_name": "Taro"
}
"""
let data = json.data(using: .utf8)!
///Decoding process
let jsonDecoder = JSONDecoder()
jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
let model = try! jsonDecoder.decode(Response.self, from: data)
print(model)
The end
Recommended Posts