我无法将我的模型翻译成字典。我的模型从 Codable 继承,当使用 JSONSerialization 时,我得到一个字典,格式如下:
(...,"sensors": <__NSArrayI 0x1105324f0>( {
accx = "-0.002471923828125";
accy = "0.011444091796875";
accz = "-1.013595581054688";
gyrox = "-0.029818882093399213";
gyroy = "0.028939506301455049";
gyroz = "0.0044943506556177227"; }, ...)
(请注意,我的键不是字符串,而是值)
当实际上想要这个时:
(..., "sensors": [ {
"accx" = -0.002471923828125;
"accy" = 0.011444091796875;
"accz" = -1.013595581054688;
"gyrox" = -0.029818882093399213;
"gyroy" = 0.028939506301455049;
"gyroz" = 0.0044943506556177227;} ], ... )
我的模型是:
class Event: NSObject, Codable {
var latitude: Double?
var longitude: Double?
var speed: Double?
var date: String?
var type: String?
var sensors: [Sensor] = []
}
class Sensor: NSObject, Codable {
var accx: Double?
var accy: Double?
var accz: Double?
var gyrox: Double?
var gyroy: Double?
var gyroz: Double?
}
我用它来转换成字典:
extension Encodable {
var dictionary: [String: Any]? {
do{
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
guard let data = try? encoder.encode(self) else { return nil }
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
print(json)
return json
} catch {
return nil
}
}
}
我坚持这一点,我不知道我是否走在正确的道路上。我应该改变我组织这本词典的方式吗?