ios - 尝试使用 Swift 将类型 [Any] 转换为 JSON 时出错
问题描述
我正在尝试将对象类型转换[Any]
为 JSON 或我可以用来访问属性的东西。
脚步:
- 我从库中调用一个函数来连接到蓝牙设备并从它的内存中检索数据:
device.getMemoryData(totalCount: { (count) in
print("There are \(count) elements in the memory")
}, dataArray: { (data) in
print("DATA --> \(data)")
self.processReceivedData(data)
// Here is where I receive the [Any] object
})
在步骤 1 中打印的接收到的对象符合以下内容:
[{
side = 0;
dataID = 07ebcd0070bf9a8116a8898e673e96e4;
valueA = 69;
valueC = 60;
valueD = 0;
irregular = 0;
angleChange = 4;
startAngle = 34;
valueB = 106;
time = "2015-01-01 13:33:00 +0000";
},
{
side = 0;
dataID = 0cf80347a86013689586d01d1d80fca5;
valueA = 69;
valueC = 60;
valueD = 0;
irregular = 0;
angleChange = 2;
startAngle = 37;
valueB = 106;
time = "2015-01-01 15:06:00 +0000";
}]
- 尝试访问对象包含的信息:
我尝试JSONSerialization
:
function processReceivedData(data:[Any]) {
guard let processedData = try? JSONSerialization.data(withJSONObject: data, options: []) as? [[String: Any]] else {
print("ERROR")
return
}
print("JSON: \(processedData)")
// Run error when trying to serialize: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSTaggedDate)'
*** First throw call stack:
}
我也尝试使用以下方法对其进行迭代,for
但出现编译错误:
function processReceivedData(data:[Any]) {
for item in data {
for (id, object) in item {
print("ID: \(id), Object: \(object)")
}
}
}
// Compile error: Type 'Any' does not conform to protocol 'Sequence'
我需要访问数据以检查哪个位置具有最旧的时间戳并获取值。如何访问数据?
解决方案
正如评论的那样,你是data
一个NSArray
。NSDictionary
您无需转换为 JSON 即可访问属性。
尝试这个:
func processReceivedData(data:[Any]) {
for item in data {
if let item = item as? [String: Any] {
for (id, object) in item {
print("ID: \(id), Object: \(object)")
}
} else {
print("Unexpected element: \(item)")
}
}
}
推荐阅读
- python - 展开和提取文本
- java - Spring Role Base 身份验证微服务应用程序
- java - java.sql.SQLNonTransientConnectionException:需要 CLIENT_PLUGIN_AUTH
- php - 在laravel中将数字四舍五入到最接近的9
- kotlin - 清单未达到活动
- java - 线程安全问题 - 没有得到预期的答案
- android - 使用 TextField Flutter 选择购物车数量
- python - 如何在 tkinter 中根据不同大小的计算机屏幕放置小部件
- python - BeautifulSoup 没有读取相同的 HTML 源代码
- java - 选择 FromDate 时出错