gpt4 book ai didi

ios - Swift 将数据映射到 [String : Any]

转载 作者:搜寻专家 更新时间:2023-10-31 22:09:45 25 4
gpt4 key购买 nike

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

Cannot force unwrap value of non-optional type 'Data'

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,然后消息发生:

Value of optional type '[String : Any]?' not unwrapped; did you mean to use '!' or '?'?

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

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

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

最佳答案

您使用了错误的 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]

关于ios - Swift 将数据映射到 [String : Any],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51131536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com