-1

I have to encode a [String:Any] object to a JSON like this:

{
  "timestamp": "2021-06-17T09:18:30.212Z",
  "readings": [
    {
      "uuid": "string",
      "major": 0,
      "minor": 0,
      "macAddress": "string",
      "rssi": 0
    }
  ]
}

I have a Codable class to handle "readings":

class BeaconData: Codable {
    var uuid: String
    var major: Int
    var minor: Int
    var rssi: Double
    
    init(uuid: String, major: Int, minor: Int, rssi: Double) {
        self.uuid = uuid
        self.major = major
        self.minor = minor
        self.rssi = rssi
    }
}

While timestamp is a String. I created a [String:Any] object to contain those data:

let parameters = ["timestamp": myTimestampString, "readings": myArrayOfBeaconData]

...but if I try to encode it with JSONEncoder

let data = JSONEncoder().encode(parameters)

...it returns that:

Protocol 'Any' as a type cannot conform to 'Encodable'

Any suggestions on how to organize those data to encode them without creating a new Root struct?

Luciano
  • 1,208
  • 2
  • 17
  • 36
  • You can't use Any when using Codable and please add code that is causing the issue to your question. Most likely you just need another root struct that holds the timestamp and an array of BeaconData – Joakim Danielson Jun 17 '21 at 09:27
  • @JoakimDanielson I know that another root struct could solve the problem, but It's not maintainable. The code that is causing the issue is JSONEncoder().encode(parameters), where parameters is a [String:Any] object. I asked for a solution to structure those data in a way that allows me to encode... – Luciano Jun 17 '21 at 09:51
  • I don’t understand what you mean by not maintainable and you didn’t update your question with any more code or clearer requirements so overall it’s hard to understand what kind of solution you need. – Joakim Danielson Jun 17 '21 at 10:01
  • I mean that I can't create a new struct for each case like this, there could be a lot. I'm just asking if there is a solution that allows me to encode directly a [String:Any] object. I updated the code. – Luciano Jun 17 '21 at 10:09

1 Answers1

1

You must encode a model conforming to Codable , supply your timestamp and array to Root object and encode it

class BeaconData: Codable {
    var uuid: String
    var major: Int
    var minor: Int
    var rssi: Double
    
    init(uuid: String, major: Int, minor: Int, rssi: Double) {
        self.uuid = uuid
        self.major = major
        self.minor = minor
        self.rssi = rssi
    }
}

class Root: Codable {
    var timestamp: String
    var readings: [BeaconData] 
    
    init(timestamp: String, readings: [BeaconData]) {
        self.timestamp = timestamp
        self.readings = readings
       
    }
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87