I was wondering if there is a way to handle decoding JSON into a struct, when the API sending the JSON is potentially inconsistent with it's typing. In this case, it sometimes sends a property as an array, and other times as a string. I am not sure how to handle that, or if there is a nice way with Decodable. Example below. My Struct:
struct Movie: Decodable {
let title: String
let cast: [String]
let director: [String]
}
The JSON:
[{
"title": "Pulp Fiction",
"cast": [
"John Travolta",
"Uma Thurman",
"Samuel L. Jackson"
],
"director": "Quentin Tarantino"
},
{
"title": "Spider-Man: Into the Spider-Verse",
"cast": [
"John Travolta",
"Uma Thurman",
"Samuel L. Jackson"
],
"director": [
"Bob Persichetti",
"Peter Ramsey",
"Rodney Rothman"
]
}]
I am able to decode Spider-Man without an issue, but if there is only one director, it comes through as a string instead of an array. Is there a way to use Decodable for this? I know I could manually build the structs, but it would be nice to not have to. Unfortunately I have no control over the API here. Thanks in advance.