作为一个编码练习,我写了一个小程序,将Web上的MySql数据带到iPhone上.在服务器端.我编写了php脚本来获取脚本以返回json数据.
在xcode上我有
[code]
.
.
.
let jsonString = try? JSONSerialization.jsonObject(with: data!, options: [])
print(jsonString!)
.
.
.
[/code]
Run Code Online (Sandbox Code Playgroud)
在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]
Run Code Online (Sandbox Code Playgroud)
当我将jsonString传递给convertToDictionary(文本:)时
[code]
let dict = convertToDictionary(text: jsonString as! String)
[/code]
Run Code Online (Sandbox Code Playgroud)
在控制台中,我收到错误"无法将类型'__NSSingleObjectArrayI'(0x10369bdb0)的值转换为'NSString'(0x1004eac60)."
但如果我硬编码json字符串然后将其传递给convertToDictionary(文本:)
[code]
let hardCodedStr = "{\"Address\":\"1 Infinite Loop Cupertino, CA\",\"Latitude\":\"37.331741\",\"Longitude\":\"-122\",\"Name\":\"Apple\"}"
let dict = convertToDictionary(text: hardCodedStr)
print(dict!)
[/code]
Run Code Online (Sandbox Code Playgroud)
它工作得很好.这是为什么?谢谢
如果仔细查看jsonObject(with:options:)返回的内容,您将看到它是a [String: Any]或a [Any],具体取决于您的JSON.
因此,jsonString这里实际存储了一个[String: Any],甚至认为编译器认为它是类型Any:
let jsonString = try? JSONSerialization.jsonObject(with: data!, options: [])
print(jsonString!)
Run Code Online (Sandbox Code Playgroud)
如果你试图将它传递给convertToDictionary接受a的String,它当然不会起作用,因为字典String并不是兼容的类型.
如何解决这个问题呢?
问题已经解决了!你根本不需要convertToDictionary.jsonString本身就是你想要的字典.
这是你需要做的:
let jsonString = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
^^^^^^^^^^^^^^^^^
Add this part
Run Code Online (Sandbox Code Playgroud)
之后,您可以调用字典方法jsonString.我还建议你重命名jsonString为其他东西.
| 归档时间: |
|
| 查看次数: |
10150 次 |
| 最近记录: |