Other suggested solutions handle type of structure they are part of, While I am not able to figure out how to parse nested part of that same structure based on the value within outer structure.
I have a JSON response whose structure change based on one of the values within outer part of JSON.
For example:
{
"reports": [
{
"reportType": "advance",
"reportData": {
"value1": "true"
}
},
{
"reportType": "simple",
"reportData": {
"value3": "false",
"value": "sample"
}
}
]
}
Using Codable with string as Type for 'report' key fails to parse this json.
I want this report value to be either parsed later and store it as it is or atleast parse it based on the reportType
value as this have different structure for each value of reportType.
I have written code based on the the suggested solutions.
enum ReportTypes: String {
case simple, advance
}
struct Reports: Codable {
let reportArray = [Report]
}
struct Report: Decodable {
let reportType: String
let reportData: ReportTypes
enum CodingKeys: String, CodingKey {
case reportType, reportData
}
init(from decoder: Decoder) {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.reportType = try container.decode(String.self, forKey: .reportType)
switch ReportTypes(rawValue: self.reportType) {
case .simple:
???
case .advance:
???
}
}
}
Please look at the switch cases and i'm not sure what to do. I need a solution similar to do this.
Workaround:
The workaround is that to mode that reportType
inside the report {}
structure and then follow this question How can i parse an Json array of a list of different object using Codable?
New Structure
{
"reports": [
{
"reportType": "advance",
"reportData": {
"reportType": "advance",
"value1": "true"
}
},
{
"reportType": "simple",
"reportData": {
"reportType": "simple",
"value3": "false",
"value": "sample"
}
}
]
}
So it worked out for me this way.
But if changing the structure is not what you can afford then this will not work.
Other possible solution I see and later Question: How to Access value of Codable Parent struct in a nested Codable struct is storing reportType
in variable currentReportType from init(from decoder: Decoder)
and then write another decoder for struct reportData
that will handle decoding based on the value stored in var currentReportType
. Write it by following the first link shared.