0

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?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
nyarian
  • 4,085
  • 1
  • 19
  • 51
  • Seems to be Base64Encoding to me, to make the "data" readable/safe converted into a String. – Larme Dec 19 '18 at 17:26

1 Answers1

1

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.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116