我试图使用从我的restful调用返回的数据(JSON)。以下是从我的调用返回的数据(键/值对的数组,列表中每个项目总是4个键/值对):
[{"Key":"DATALOG_MAX_ID","Val":"875250","DataType":1,"Description”:”N/A.”},{“Key":"SNAPSHOT_DATALOG_ID","Val":"875259","DataType":1,"Description”:”N/A“},{“Key":"SNAPSHOT_FILE_SIZE","Val":"492590686","DataType":1,"Description”:”N/A“},{“Key":"SNAPSHOT_GEN_ID","Val":"770","DataType":1,"Description”:”N/A”},{“Key":"SNAPSHOT_LAST_UPDATED","Val":"2017-04-14 00:01:17.240","DataType":6,"Description”:”N/A“},{“Key":"SNAPSHOT_MAX_ID","Val":"374418","DataType":1,"Description”:”N/A”},{“Key":"SNAPSHOT_READY","Val":"0","DataType":4,"Description”:”N/A”},{“Key":"SNAPSHOT_REQUIRES_BUILD","Val":"1","DataType":4,"Description”:”N/A”}]
如果我使用以下代码行反序列化:
let json = try JSONSerialization.jsonObject(with: data!, options: []) as![Dictionary<String, Any>]
它成功但值仅出现在数组中每个字典的4个键/值对中的2个中。如果您单步执行并检查变量,我会注意到Builtin.rawpointer对于缺少的值总是0x0。
奇怪的是,如果我尝试使用以下行反序列化:
let json = try JSONSerialization.jsonObject(with: data!, options: []) as![MetaDataEntry]
奇怪的是,它成功了,我可以看到所有数据都在那里(见下面的截图)。
答案 0 :(得分:1)
这适用于我,但我必须修复一些引号
let jsonString = "[{\"Key\":\"DATALOG_MAX_ID\",\"Val\":\"875250\",\"DataType\":1,\"Description\":\"N/A.\"},{\"Key\":\"SNAPSHOT_DATALOG_ID\",\"Val\":\"875259\",\"DataType\":1,\"Description\":\"N/A\"},{\"Key\":\"SNAPSHOT_FILE_SIZE\",\"Val\":\"492590686\",\"DataType\":1,\"Description\":\"N/A\"},{\"Key\":\"SNAPSHOT_GEN_ID\",\"Val\":\"770\",\"DataType\":1,\"Description\":\"N/A\"},{\"Key\":\"SNAPSHOT_LAST_UPDATED\",\"Val\":\"2017-04-14 00:01:17.240\",\"DataType\":6,\"Description\":\"N/A\"},{\"Key\":\"SNAPSHOT_MAX_ID\",\"Val\":\"374418\",\"DataType\":1,\"Description\":\"N/A\"},{\"Key\":\"SNAPSHOT_READY\",\"Val\":\"0\",\"DataType\":4,\"Description\":\"N/A\"},{\"Key\":\"SNAPSHOT_REQUIRES_BUILD\",\"Val\":\"1\",\"DataType\":4,\"Description\":\"N/A\"}]"
let data = jsonString.data(using: String.Encoding.utf8)!
if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as?[[String:AnyObject]] {
for row in json {
print(row)
}
}
输出:
["Val": 875250, "Key": DATALOG_MAX_ID, "DataType": 1, "Description": N/A.]
["Val": 875259, "Key": SNAPSHOT_DATALOG_ID, "DataType": 1, "Description": N/A]
["Val": 492590686, "Key": SNAPSHOT_FILE_SIZE, "DataType": 1, "Description": N/A]
["Val": 770, "Key": SNAPSHOT_GEN_ID, "DataType": 1, "Description": N/A]
["Val": 2017-04-14 00:01:17.240, "Key": SNAPSHOT_LAST_UPDATED, "DataType": 6, "Description": N/A]
["Val": 374418, "Key": SNAPSHOT_MAX_ID, "DataType": 1, "Description": N/A]
["Val": 0, "Key": SNAPSHOT_READY, "DataType": 4, "Description": N/A]
["Val": 1, "Key": SNAPSHOT_REQUIRES_BUILD, "DataType": 4, "Description": N/A]