Search code examples
jsonswiftnsdatacodablejsonencoder

Swift: inner Data-typed variable was encoded via JSONEncoder. How to deserialize it properly?


Consider the next example:

import Foundation 

class UDFrame: Codable {

    var data:Data

    init(data:Data) {
        self.data = data
    }

}


class Event: Codable {

    var name:String

    init(name:String) {
        self.name = name
    }

}

let encoder = JSONEncoder()
let event = Event(name: "eventName")
let serializedEvent = try encoder.encode(event)
let frame = UDFrame(data: serializedEvent)
let serializedFrame = try encoder.encode(frame)
print(String(data: serializedFrame, encoding: String.Encoding.utf8)!)

Result of the print statement is next: {"data":"eyJuYW1lIjoiZXZlbnROYW1lIn0="}.

My question is how to get "eventName" out of this drivel?

And, if possible, could you please explain why Data is serialized in such way by JSONEncoder, and what's the way to get initial data on another platform when such a JSON is given?


Solution

  • You can simply use JSONDecoder for decoding a JSON-encoded Data.

    Data is simply base64encoded, so you just need to base64 decode it on another platform to get back the original data. However, there's no need to store a JSON-encoded object as a property of another object, you can simply use the JSON-encoded object.