首页 > 解决方案 > 无法将数据转换为 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"}]

错误发生在哪里?

标签: jsonswiftnsjsonserialization

解决方案


[ ]表示 JSON 中的数组。{ }意思是字典。你有一个字典数组。请注意,当您在 Swift 中打印数组时,您会看到( ).

不要在没有非常清楚理解和具体原因的情况下在 Swift 中使用NSArrayor 。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 {


推荐阅读