Swift 3.0:将数据转换为JSON [String:Any] [英] Swift 3.0: Data to JSON [String : Any]

查看:352
本文介绍了Swift 3.0:将数据转换为JSON [String:Any]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

In this code I'm trying to convert Data into JSON as a dictionary [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)
         }

推荐答案

正确的方法是:

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

感谢 Eric Aya

这篇关于Swift 3.0:将数据转换为JSON [String:Any]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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