且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Swift 3 中将 JSON 字符串转换为字典

更新时间:2022-11-19 10:28:52

如果您仔细查看 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.