JSONSerialization使用错误的类型序列化字典

时间:2018-04-13 22:35:27

标签: swift nsjsonserialization jsonencoder

我无法将模型翻译成字典。 我的模型继承自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
    }
}
}

我坚持这个,我不知道我是否走正路。 我应该改变组织这本字典的方式吗?

1 个答案:

答案 0 :(得分:1)

您正在查看NSDictionary.description的结果,而NSDictionary.description的结果是不是 JSON,并不一定是所包含对象的准确表示。

解码没有实际问题。例如:

Welcome to Apple Swift version 4.0.3 (swiftlang-900.0.74.1 clang-900.0.39.2). Type :help for assistance.
  1> import Foundation
  2> let json = "{ \"sensors\": [ { \"accx\": 0.011444091796875 } ] }"
json: String = "{ \"sensors\": [ { \"accx\": 0.011444091796875 } ] }"
  3> let d = try! JSONSerialization.jsonObject(with: json.data(using: .utf8)!, options: []) as! [String: Any] 
d: [String : Any] = 1 key/value pair {
  [0] = {
    key = "sensors"
    value = {
      payload_data_0 = 0x0000000100111ad0
      payload_data_1 = 0x0000000000000000
      payload_data_2 = 0x0000000000000000
      instance_type = 0x00000001014179c8 libswiftCore.dylib`InitialAllocationPool + 4888
    }
  }
}

当我们打印JSONSerialization返回的字典时,我们会在引号中看到数字:

  4> print(d)
["sensors": <__NSSingleObjectArrayI 0x100111ad0>(
{
    accx = "0.011444091796875";
}
)
]

但是当我们实际从嵌套容器中提取数字时,它实际上是Double

  5> ((d["sensors"] as! [Any])[0] as! [String: Any])["accx"] as! Double
$R0: Double = 0.011444091796875

故事的寓意:不要指望对象的description是其值的准确序列化。如果您需要准确的序列化,请将对象转换为JSON或属性列表,或在调试器中检查它。