gpt4 book ai didi

ios - 在 Swift 中使用 Codable 解析 JSON 响应

转载 作者:行者123 更新时间:2023-11-28 09:21:39 25 4
gpt4 key购买 nike

我将收到带有对象数组的 JSON 形式的 API 响应。例如,

{
"Header": "Verification",
"Info": [
{
"mobile": "**** **** 123"
},
{
"email": "s******k**@g***.com"
}
],
}

我使用了 Codable 特性并创建了一个结构,如下所示,

struct cResponse: Codable 
{
var Header: String?
var Info: [Info]
}

struct Info: Codable {
var mobile: String!
var email: String!
}

我正在尝试像下面的代码一样快速使用 JSONDecoder 解码 JSON 响应,

let decoder = JSONDecoder()
let decodedcRES: cResponse = try decoder.decode(cResponse.self, from: CData)

这工作正常,直到来自服务器的信息只有移动设备和电子邮件。

但是 Info 在运行时将是动态的(即)我将从服务器的 Info 下接收更多 JSON 对象。因此,如果我创建如下结构,

struct cResponse: Codable 
{
var Header: String?
var Info: [String]
}

我收到“无法读取数据,因为它的格式不正确。”作为错误。

如何使用 Codable 功能在 swift 中处理动态 JSON 数组对象?

最佳答案

信息键包含对象数组,因此将您的结构更改为:

struct cResponse: Codable
{
var Header: String?
var Info: [[String: String]]
}

关于ios - 在 Swift 中使用 Codable 解析 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57901569/

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