【问题标题】:Swift Mapping Data to [String: Any]Swift 将数据映射到 [String: Any]
【发布时间】:2018-07-02 08:02:45
【问题描述】:

我想将数据类型转换为 [String: Any],但 JSONSerialization 告诉我:

无法强制解开非可选类型“数据”的值

var json: [String: Any]
            do{
                let jsonEncoder = JSONEncoder()
                let encodedJson = try jsonEncoder.encode(message)
                json = try JSONSerialization.data(withJSONObject: encodedJson!, options: []) as? [String : Any]
            } catch {
                log.error(error.localizedDescription)
            }
return .requestParameters(parameters: json, encoding: JSONEncoding.default)

如果我删除“!”来自encodedJson,然后消息发生:

可选类型 '[String : Any]?' 的值未拆封;你的意思是用'!'还是“?”?

如果我删除“?”从任何?,然后我使用json而不初始化它,当然

不知道如何解决这个问题(新的 swift 编码器)

希望这不是一个愚蠢的问题

【问题讨论】:

  • 请多分享一些代码,特别是message变量的值是多少?

标签: ios swift dictionary moya json-serialization


【解决方案1】:

您使用了错误的 API,data(withJSONObject 从数组或字典创建 Data

你需要反过来。要解决问题,请删除encodedJson之后的感叹号

json = try JSONSerialization.jsonObject(with: encodedJson) as? [String : Any]

并将json 声明为可选

var json: [String: Any]?

或者 – 如果 JSON 保证始终是字典 – 强制解包对象

json = try JSONSerialization.jsonObject(with: encodedJson) as! [String : Any]

【讨论】:

    【解决方案2】:

    没有必要这样做,因为您已经拥有encodedJson中的数据

    json = try JSONSerialization.data(withJSONObject: encodedJson!, options: []) as? [String : Any]
    

    因为 withJSONObject 需要一个对象不是 Data ,所以也将其转换为 [String:Any] 将失败

    【讨论】:

    • 好的,谢谢 :) ,但是如何将我的 encodedJson 转换为 [String: Any]?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多