Problem basically comes down to this. My app is receiving messages in this JSON format:
{
"action": "ready",
"data": null
}
or
{
"action": "error",
"data": {
"code": String,
"exception": String,
"status": Int
}
}
or
{
"action": "messageRequest",
"data": {
"recipientUserId": String,
"platform": String,
"content": String
}
}
or
{
"action": "tabsChange",
"data": {
"roomsTabs": [{
"configuration": {
"accessToken": STRING,
"url": STRING,
"userId": STRING
},
"id": STRING,
"isOnline": BOOLEAN,
"isUnread": BOOLEAN,
"lastActive": NUMBER,
"name": STRING,
"participantBanned": BOOLEAN,
"platform": STRING,
"secondParticipant": {
"id": STRING,
"platform": STRING,
"userId": STRING
},
"secondParticipantId": STRING,
"state": STRING,
"unreadMessages": NUMBER
]}
}
}
As you can see the data object has different structure depending on a message and it can get large (and there's more than 10 of them). I don't want to parse everything by hand, field-by-field, ideal solution would of course be:
struct ChatJsCommand: Codable {
let action: String
let data: Any?
}
self.jsonDecoder.decode(ChatJsCommand.self, from: jsonData))
Of course because of Any this can't conform to Codable. I can of course extract manually only the action field, create a map of actions (enum) to struct types and then do JSONDecoder().decode(self.commandMap[ActionKey], data: jsonData)
. This solution would probably also require some casting to proper struct types to use the objects after parsing.
But maybe someone has a better approach? So the class isn't 300 lines? Any ideas greatly appreciated.