I am trying to parse nested data from JSON response but not getting success. Below is what i tried so far and the json response trying to parse.
// JSON
{
"statusCode": 200,
"success": true,
"data": {
"tDetail": [
{
"roleId": null,
"id": 34,
"userId": 126,
"catId": null,
"importId": null,
"name": "My task from postman",
"myday": 1,
"important": 0,
"completed": 0,
"dateCreated": "2020-02-10T09:05:04.000Z",
"dateModified": "2020-02-10T09:05:04.000Z"
}
],
"steps": [],
"files": [],
}
}
// Struct
struct MyDayAndTaskDetails: Codable
{
let data : [MyTaskDetail]
}
struct MyTaskDetail : Codable {
let roleId, taskId, userId, catId, important, completed, recurring, myday : Int?
let repeatType, name, duedate, reminder, frequency, weekdays, notes, baseurl : String?
let steps : [Steps]
let files : [Files]
private enum CodingKeys: String, CodingKey {
case taskId = "id"
case userId = "userId"
case roleId = "roleId"
case catId = "catId"
case myday = "myday"
case name = "name"
case notes = "notes"
case duedate = "duedate"
case reminder = "reminder"
case recurring = "recurring"
case repeatType = "repeatType"
case important = "important"
case completed = "completed"
case frequency = "frequency"
case weekdays = "weekdays"
case baseurl = "baseurl"
case steps = "Steps"
case files = "Files"
}
}
struct Steps : Codable {
let stepName : String?
let status, stepId : Int?
private enum CodingKeys: String, CodingKey {
case stepName = "stepName"
case status = "status"
case stepId = "stepId"
}
}
struct Files : Codable {
let fileName : String?
private enum CodingKeys: String, CodingKey {
case fileName = "fileName"
}
}
You missed one level
struct MyDayAndTaskDetails: Codable {
let data : Detail
}
struct Detail: Codable {
let tDetail: [MyTaskDetail]
let steps : [Steps]
let files : [Files]
}
and so on
Use this structs, below structs are sufficient for given json. If you have more keys in your json then you can add them into their respective structs.
struct MyDayAndTaskDetails : Codable {
let data : Task?
let statusCode : Int?
let success : Bool?
}
struct Task : Codable {
let files : [Files]?
let steps : [Steps]?
let tDetail : [TDetail]?
}
struct TDetail : Codable {
let catId : String?
let completed : Int?
let dateCreated : String?
let dateModified : String?
let id : Int?
let importId : String?
let important : Int?
let myday : Int?
let name : String?
let roleId : String?
let userId : Int?
}
struct Steps : Codable {
let stepName : String?
let status: Int?
let stepId : Int?
}
struct Files : Codable {
let fileName : String?
}
And decode data with
let decoder = JSONDecoder()
let response = try decoder.decode(MyDayAndTaskDetails.self, from: data)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.