I tried a lot of different methods but none really helps. I need to read in data that has a set of expected keys and a range of unknown keys. All must be read in. For example the json is like this;
{
"name": "",
"age": null,
"street": "",
"appended/1": null,
"appended/2": null,
"appended/3": null
}
The struct and coding keys for name, age and street is obvious. But how do I get to the 'appended/1' , 'appended/2' etc ? this list can be quite long and I would like to programmatically fetch the data.
I have tried ;
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
name = try container.decodeIfPresent(String.self, forKey: .name) ?? ""
etc.
}
The above will only fetch the name and other codingkeys that are defined, and obviously works as expected. If have tried to work with dynamic coding keys like so ;
init(from decoder: Decoder) throws {
let dynamicKeysContainer = try decoder.container(keyedBy: DynamicCodingKey.self)
var appended: [Appended] = []
try dynamicKeysContainer.allKeys.forEach { key in
if key.stringValue.starts(with: "appended/"), let appendedNumber = Int(key.stringValue.split(separator: "/")[1]) {
appendedFound.append = try dynamicKeysContainer.decode([Appended].self, forKey: key)
}
}
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
name = try container.decodeIfPresent(String.self, forKey: .name) ?? ""
appended = appendedFound
}
however doing this, will put the 'cursor' of the decoder at the end of the file when it is done decoding the dynamic keys. And I cannot fetch my data using my regular coding keys.
How can this be done?