0

I have a struct Message in Swift, which has a property data.

struct Message {
  let id: Int
  let data: Data
}

I want to decode the struct Message from JSON, where it's data property's underlying type cannot be determined. An example JSON would be like:

{
  "id": 3,
  "data": {
    "name": "Bob",
    "age": 32
  }
}

or:

{
  "id": 3,
  "data": {
    "location": "New York",
    "data": "2022-3-1"
  }
}

Therefore, I'd like to store the data as type Data, and defer the actual decoding of data to later time. Now, I just want to store the raw data. How should I achieve that in Swift? Thanks for helping.

wheatset
  • 339
  • 1
  • 7
  • You can’t decode json into Data and you can’t decode only part of the json so the answer is you cannot do this. – Joakim Danielson Apr 20 '23 at 15:52
  • That's right but you might have a work-around; https://stackoverflow.com/questions/46999079/swift-4-decodable-decoding-json-object-into-data – john elemans Apr 20 '23 at 16:13
  • 3
    You get `Data` only if the API sends something like base64 encoded bytes. If the structure of the JSON cannot be determined use `JSONSerialization`. The magic of `Codable` is based on (rather) predictable JSON. Somewhere there is a `AnyCodable` implementation, but the effort is much higher and the efficiency is much lower than traditional `JSONSerialization`. – vadian Apr 20 '23 at 16:25

0 Answers0