Json синтаксический анализ ответа в кодируемую строку для обнаружения ошибки KeyNotFound. KeyNotFound при кодировании в класс оболочки
Unexpected error: keyNotFound(CodingKeys(stringValue: "id", intValue: nil),
Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil)],
debugDescription: "No value associated with key CodingKeys(stringValue: \"id\", intValue: nil)
(\"id\").", underlyingError: nil)).
Данные ответа
{
"msg": {
"success": [
""
]
},
"data": {
"jobs": {
"current_page": 1,
"data": [
{
"id": 154,
"user": "UserName"}
]
}
}
}
Сервисный вызов
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
print("error: \(error)")
} else {
if let response = response as? HTTPURLResponse {
print("statusCode: \(response.statusCode)")
}
if let data = data, let dataString = String(data: data, encoding: .utf8) {
let jsonData = dataString.data(using: .utf8)!
do {
let jsonDecoder = JSONDecoder()
let user = try jsonDecoder.decode(JobListModel.self, from: data)
print("Hello \(user.msg )")
} catch {
print("Unexpected error: \(error).")
}
}
}
}
ModelClass.
struct JobListModel: Codable {
let msg: Msg
let data: Data
private enum CodingKeys: String, CodingKey {
case msg = "msg"
case data = "data"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
msg = try values.decode(Msg.self, forKey: .msg)
data = try values.decode(Data.self, forKey: .data)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(msg, forKey: .msg)
try container.encode(data, forKey: .data)
}
}