在 Swift 3 中将 JSON 字符串转换为字典 [英] Convert a JSON string to Dictionary in Swift 3

查看:45
本文介绍了在 Swift 3 中将 JSON 字符串转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为编码练习,我编写了一个小程序,将来自 Web 的 MySql 数据传输到 iPhone.在服务器端.我写了php脚本,获取脚本返回json数据.

as a coding exercise, I wrote a small program to take MySql data frm the web to the iPhone. On the server side. I wrote the php script to get the script to return the json data.

我在 xcode 上有

On xcode I have

[code]
.
.
.
     let jsonString = try? JSONSerialization.jsonObject(with: data!, options:    [])
    print(jsonString!)
    .
    .
    .
[/code]

在 xcode 控制台中,我有这个:

In xcode console, I have this:

[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:)

When I pass the jsonString to convertToDictionary(text:)

[code]
let dict = convertToDictionary(text: jsonString as! String)
[/code]

在控制台中,我收到错误消息无法将类型为‘__NSSingleObjectArrayI’(0x10369bdb0)的值转换为‘NSString’(0x1004eac60)."

In the console I get an error "Could not cast value of type '__NSSingleObjectArrayI' (0x10369bdb0) to 'NSString' (0x1004eac60)."

但是如果我对 json 字符串进行硬编码,然后将其传递给 convertToDictionary(text:)

but if I hard code the json string then pass it to the 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] 

它工作得很好.这是为什么?谢谢

It works just fine. Why is that? Thanks

推荐答案

如果您仔细查看 jsonObject(with:options:) 返回的内容,您会发现它是一个 [字符串:Any][Any],具体取决于您的 JSON.

If you look closely at what jsonObject(with:options:) returns, you will see that it is a [String: Any] or a [Any], depending on your JSON.

因此,jsonString这里实际上存储的是一个[String: Any],甚至认为编译器认为它是Any类型:

Therefore, jsonString here actually stores a [String: Any], even thought the compiler thinks it is of type Any:

let jsonString = try? JSONSerialization.jsonObject(with: data!, options:    [])
print(jsonString!)

如果您尝试将其传递给接受 StringconvertToDictionary,它当然不会起作用,因为字典和 String是不兼容的类型.

If you try to pass this to convertToDictionary, which accepts a String, it of course will not work, because a dictionary and String are not compatible types.

如何解决这个问题?

问题已经解决了!您根本不需要 convertToDictionary.jsonString 本身你想要的字典.

The problem is already solved! You don't need convertToDictionary at all. jsonString itself is the dictionary you wanted.

这是你需要做的:

let jsonString = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
                                                                             ^^^^^^^^^^^^^^^^^
                                                                             Add this part

之后,您可以在 jsonString 上调用字典方法.我还建议您将 jsonString 重命名为其他名称.

After that you can call dictionary methods on jsonString. I also suggest you to rename jsonString to something else.

这篇关于在 Swift 3 中将 JSON 字符串转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆