I'm trying to decode the following JSON in Swift 4:
{
"token":"RdJY3RuB4BuFdq8pL36w",
"permission":"accounts, users",
"timout_in":600,
"issuer": "Some Corp",
"display_name":"John Doe",
"device_id":"uuid824fd3c3-0f69-4ee1-979a-e8ab25558421"
}
The problem is, the last 2 elements (display_name
and device_id
) in the JSON may or may not exist or the elements could be named something entirely different but still unknown, i.e "fred": "worker", "hours" : 8
So what I'm trying to achieve is decode what IS known, i.e token
, permission
, timeout_in
and issuer
and any other elements (display_name
, device_id
etc) place them into a dictionary.
My structure looks like this:
struct AccessInfo : Decodable
{
let token: String
let permission: [String]
let timeout: Int
let issuer: String
let additionalData: [String: Any]
private enum CodingKeys: String, CodingKey
{
case token
case permission
case timeout = "timeout_in"
case issuer
}
public init(from decoder: Decoder) throws
{
let container = try decoder.container(keyedBy: CodingKeys.self)
token = container.decode(String.self, forKey: .token)
permission = try container.decodeIfPresent(String.self, forKey: .permission).components(separatedBy: ",")
timeout = try container.decode(Int.self, forKey: . timeout)
issuer = container.decode(String.self, forKey: .issuer)
// This is where I'm stuck, how do I add the remaining
// unknown JSON elements into additionalData?
}
}
// Calling code, breviated for clarity
let decoder = JSONDecoder()
let accessInfo = try decoder.decode(AccessInfo.self, from: data!)
Being able to decode a parts of a known structure where the JSON could contain dynamic info as well is where I'm at if anyone could provide some guidance.
Thanks