json - 无法将数据转换为 NSDictionary
问题描述
我正在尝试将数据从 URLSession 转换为 NSDictionary,但在将数据转换为字典时失败。
下列的:
let json = try? JSONSerialization.jsonObject(with: data!, options: [])
print(json ?? "NotWorking")
输出
(
{
babyId = 1;
id = 17;
timestamp = "2018-06-30 09:23:27";
}
)
但是当我尝试将其转换为字典时,它会输出 nil。
let json = try? JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
网页输出
[{"id":"17","babyId":"1","timestamp":"2018-06-30 09:23:27"}]
错误发生在哪里?
解决方案
[ ]
表示 JSON 中的数组。{ }
意思是字典。你有一个字典数组。请注意,当您在 Swift 中打印数组时,您会看到( )
.
不要在没有非常清楚理解和具体原因的情况下在 Swift 中使用NSArray
or 。NSDictionary
使用正确类型的 Swift 数组和字典。
您的代码应该是:
do {
if let results = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
// results is now an array of dictionary, access what you need
} else {
print("JSON was not the expected array of dictonary")
}
} catch {
print("Can't process JSON: \(error)")
}
真的你不应该使用data!
任何一个。在此之上的某个地方,您应该有一个if let data = data {
推荐阅读
- rust - Rust - 由于需求冲突,无法为 autoref 推断出合适的生命周期
- opencl - 如何监控 OpenCL 主机代码的运行时行为
- java - 将 Java 转换为 Python - 将属性值转换为字符串
- c# - 哪个是使用数据库上下文存储库模式的最佳代码?
- swift - 如何验证单元格在我的 UI 测试中是否可见
- c# - 如何在 3D 中选择平面和三角形边缘之间的两个正确交点之一?
- tmux - Linux tmux 捕获窗格到文件
- javascript - 如何使用Jquery在页面上的许多div中获取表单中的数据
- apache-kafka - Kafka 中使用了哪些内部主题?
- material-ui - 网格组件对齐