This is my first time using the swift 4 codable protocol in an app.
I'm given a json response like this -
{
"result": [
{
"id": 1,
"heading": "Chapter 1",
"headingTextColor": "#3e9690",
"title": "Introduction: inovation for crisis",
"coverImage": "https://www.country067.com/wp-content/uploads/sites/28/2017/07/logoImage_4.jpg",
"descriptionUrl": "This is an option attribute. If not null this chapter will probably has no sections",
"sections": [
{
"id": 1,
"title": "Background",
"url": "http://api.example.com/chapter/1/section/1",
"projects": "null"
},
{
"id": 2,
"title": "Projects",
"url": null,
"projects": [
{
"id": 1,
"title": "Support to refugees",
"url": "http://api.example.com/chapter/1/project/1",
"coverImage": "https://example/wp-content/uploads/sites/28/2017/07/logoImage_4.jpg"
},
{
"id": 2,
"title": "title text",
"url": "http://api.example.com/chapter/1/project/2",
"coverImage": "https://example.com/wp-content/uploads/sites/28/2017/07/logoImage_4.jpg"
}
]
}
]
}
]
}
Using the decodable protocol, i created my models to map the response .
struct ChapterResult: Decodable {
let result: [Chapter]
}
struct Chapter: Decodable {
let id: Int
let heading: String
let headingTextColor: String
let title: String
let coverImage: String
let descriptionUrl: String
let sections: [Section]
}
struct Section: Decodable {
let id: Int
let title: String
let url: String?
let projects: [Project]?
}
struct Project: Decodable {
let id: Int
let title: String
let url: String
let coverImage: String
}
When calling the json decoder I do the following
let decoder = JSONDecoder()
let response = try decoder.decode(ChapterResult.self, from: data)
completion(.success(response.result))
which then results in the following error
failure(Optional(Error Domain=NSCocoaErrorDomain Code=4864 "Expected to decode Array but found a string/data instead." UserInfo={NSCodingPath=( "CodingKeys(stringValue: \"result\", intValue: nil)", "_JSONKey(stringValue: \"Index 0\", intValue: 0)", "CodingKeys(stringValue: \"sections\", intValue: nil)", "_JSONKey(stringValue: \"Index 0\", intValue: 0)", "CodingKeys(stringValue: \"projects\", intValue: nil)"