Swift 3.0:数据转 JSON [String : Any]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39427500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:37:25  来源:igfitidea点击:

Swift 3.0: Data to JSON [String : Any]

jsonswiftnetworkingnsdata

提问by Andrea Miotto

Evening, I'm trying to creating an APIClient, but I'm having a problem with a warning: APIClient.swift:53:81: Cast from 'Data' to unrelated type '[String : Any]' always fails

晚上,我正在尝试创建一个 APIClient,但我遇到了警告问题: APIClient.swift:53:81: Cast from 'Data' to unrelated type '[String : Any]' always fails

In this code I'm trying to convert Datainto JSONas a dictionary [String : Any].

在这段代码中,我试图将Data转换为JSON作为字典[String : Any]

I guess the compiler can't know if this cast could or could not be possible so it throws the error, but I'm pretty sure it will work. So how can I avoid this warning or how can I write safer code?

我猜编译器不知道这个转换是否可能,所以它会抛出错误,但我很确定它会起作用。那么我怎样才能避免这个警告或者我怎样才能编写更安全的代码呢?

case 200:
         do {
            let json = try JSONSerialization.data(withJSONObject: data!, options: []) as? [String : Any]
            completion(json, HTTPResponse, nil)
         } catch let error {
             completion(nil, HTTPResponse, error)
         }

回答by Andrea Miotto

The right method is:

正确的方法是:

let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : Any]

Thanks to Eric Aya

感谢Eric Aya