【发布时间】:2017-06-04 15:08:48
【问题描述】:
作为一个编码练习,我编写了一个小程序来将 MySql 数据从网络传输到 iPhone。在服务器端。我写了php脚本来获取脚本返回json数据。
在 xcode 上我有
[code]
.
.
.
let jsonString = try? JSONSerialization.jsonObject(with: data!, options: [])
print(jsonString!)
.
.
.
[/code]
在 xcode 控制台中,我有这个:
[code]
(
{
Address = "1 Infinite Loop Cupertino, CA";
Latitude = "37.331741";
Longitude = "-122";
Name = Apple;
}
)
[/code]
I have a function
[code]
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
[/code]
当我将 jsonString 传递给 convertToDictionary(text:)
[code]
let dict = convertToDictionary(text: jsonString as! String)
[/code]
在控制台中,我收到一条错误消息“无法将 '__NSSingleObjectArrayI' (0x10369bdb0) 类型的值转换为 'NSString' (0x1004eac60)。”
但如果我对 json 字符串进行硬编码,然后将其传递给 convertToDictionary(text:)
[code]
let hardCodedStr = "{\"Address\":\"1 Infinite Loop Cupertino, CA\",\"Latitude\":\"37.331741\",\"Longitude\":\"-122\",\"Name\":\"Apple\"}"
let dict = convertToDictionary(text: hardCodedStr)
print(dict!)
[/code]
它工作得很好。这是为什么?谢谢
【问题讨论】:
-
这不是你应该使用的this。此函数只是将 JSON 字符串转换为字典的便捷方式如果您只有字符串可以使用。但这不是你的情况:你有 JSON data。您应该将 data 转换为字典 - 完全忘记字符串。
-
变量
jsonString已经是一个从JSON字符串转换而来的字典。
标签: swift3