Swift, JSON Encoding/Decoding and subclasses

Swift, JSON Encoding/Decoding and subclasses

Over the past weeks I have been preparing for two CiscoLive Barcelona breakout sessions. In one of them I will give a brief demo and the other session where I will be covering parts of the Cisco Press book that I wrote. The preparation itself is not only about the slides, but also developing code that is to be used in the demo’s. These demo’s are built on iOS devices and run on some containers, so I have been writing that software in Swift, which is a beautiful and powerful programming language. One of my previous posts covers some principles of Swift. One really powerful feature is the easy capability to encode or decode data to the JSON format.  

If you want to have a class to be able to convert to and from a JSON format, just use the Codable protocol and you’re ready, see the code example below:

/*
 * Enumeration of supported message types. Extend this for new messages
 */
enum MessageType : Int, Codable {
    case unknown = 0            // default, unknown
    case acknowledgement = 255  // acknowledgement to message, if required
    case hello = 1              // hello, for keep alive, always followed by ack
    case sendMessage = 2        // send a unicast message to another client
    case broadcast = 3          // send a message to all connected clients
}

/*
 * Generic parent class
 * Every message has the following attributes
 * Version: To define which version we are talking about
 * Command of the message
 * client-id that sends the message
 */ unique request id, used for acknowledging, etc..
class Message : Codable, prettyPrint  {
    var version : String = "1.0"
    var msgType : MessageType = .unknown
    var clientId: String = "" // client host, generated by the server to guarantee
    var requestId: String = UUID.init().uuidString  // unique request id for this message, used in the ack
    
    // Default constructor
    // Not used cause calling super.init can override msgType value
    init() {
        // empty on purpose
    }
}
This code example defines a class message with variables for messageType (of type MessageType), requestId, which is a unique UUID string value, and a data variable which can contain any String. So let’s say I create a new message , called hello with the data “Hello there!” with the following code sample:
let msg = Message()
msg.msgType = .hello
msg.data = "Hello There!"

To convert this to JSON, this would only require a few lines of code:

let encoder = JSONEncoder()
let jsonData = try encoder.encode(msg)

The variable jsonData (of type Data) now contains a JSON-version of the earlier created message. Just to check the output, I can use the following commands to convert that data to String and output it in XCode’s Playground. 

let jsonDataAsString = String(data: jsonData, encoding: .utf8)

Suppose you would like to extend our message class with a special broadcast message, where the message can be sent to a all endpoints.. You could add an optional broadcastContent variable to the message class and create a state machine to determine when to use that value. Another alternative is to leverage the power of object-oriented programming and create a new subtype, like the following code example:

/*
 * BroadcastMessage is used to broadcast a message to all connected clients
 */
class BroadcastMessage : Message {
    // response message
    var msgContent : String = ""   // Message to broadcast   
}

So when you’d create a multicast message, like below, you’d expect that it would contain all attributes in the json file, right? Let’s check it out in Playground:

As you can see, the output does not contain all attributes of the broadcast message! It only contains the base message type class values. The msgContent variable is not included. It took me some time debugging and researching to figure out what happens. Swift bug SR-5431 and SR-4722  provide more details. Without going into those bugs, it comes down to the fact that as soon as you subclass a class that conforms to Codable, you need to override the default encode/decode methods and write your own. After some fiddling around, I have used the following code pattern to achieve that result.

/* Generic parent class
 * Every message has the following attributes
 * Version: To define which version we are talking about
 * Command of the message
 * client-id that sends the message
 * unique request id, used for acknowledging, etc..
 */
class Message : Codable, prettyPrint  {
    var version : String = "1.0"
    var msgType : MessageType = .unknown
    var data: String = "" // client host, generated by the server to guarantee
    var requestId: String = UUID.init().uuidString  // unique request id for this message, used in the ack
    
    private enum CodingKeys: CodingKey {
        case version, msgType, data, requestId
    }
    
    
    // Default constructor
    // Not used cause calling super.init can override msgType value
    init() {
        // empty on purpose
    }
    
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        version = try container.decode(String.self, forKey: .version)
        msgType = try container.decode(MessageType.self, forKey: .msgType)
        data = try container.decode(String.self, forKey: .data)
        requestId = try container.decode(String.self, forKey: .requestId)
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(version, forKey: .version)
        try container.encode(msgType, forKey: .msgType)
        try container.encode(data, forKey: .data)
        try container.encode(requestId, forKey: .requestId)
    }
}

/*
 * BroadcastMessage is used to broadcast a message to all connected clients
 */
class BroadcastMessage : Message {
    // response message
    var msgContent : String = ""   // Message to broadcast
    
    // coding keys enumeration used for JSON encoding/decoding
    private  enum CodingKeys: CodingKey {
        case msgContent
    }
    
    // set class variables
    private func initClassVars() {
        self.msgType = .broadcast
        msgContent = ""
    }
    
    // default constructor. Call the parent and set variables
    override init() {
        super.init()
        initClassVars()
    }
    
    // Constructor used to instantiate a class from JSON Data
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        msgContent = try container.decode(String.self, forKey: .msgContent)
        try super.init(from: decoder)
    }
    
    // Method used to encode class to JSON
    override public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(msgContent, forKey: .msgContent)
        try super.encode(to: encoder)
    }
}

As you can see, when BroadcastMessage is converted to JSON, it is now correctly encoded.

I am now using the coding pattern below to achieve this functionality:

  • Create a private enum called CodingKeys that follows CodingKey. ]
  • Enter all class variables as part of the enumeration
  • Create custom encoders and decoders for the base class
  • In the subclass, define a new private enum called CodingKeys . I have marked both private so the compiler knows which variable to know in which function
  • Create the custom encoders
  • Encode the variables of the child class and then
  • Call the encoder / decoder of the parent class