-2

我必须将 [String:Any] 对象编码为 JSON,如下所示:

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

我有一个 Codable 类来处理“读数”:

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
    }
}

而时间戳是一个字符串。我创建了一个 [String:Any] 对象来包含这些数据:

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

...但是如果我尝试使用 JSONEncoder 对其进行编码

let data = JSONEncoder().encode(parameters)

...它返回:

协议“任何”作为一种类型不能符合“可编码”

关于如何组织这些数据以对其进行编码而不创建新的 Root 结构的任何建议?

4

1 回答 1

1

您必须对符合的模型进行编码Codable,将时间戳和数组提供给Root对象并对其进行编码

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
       
    }
}
于 2021-06-17T09:31:24.500 回答