【发布时间】:2021-11-26 15:31:16
【问题描述】:
收到 Json 响应
{
"data": [
{
"key": "email",
"value": "qfmppddybsfeiiiazh@mrvpt.com"
},
{
"key": "name",
"value": "Tg baa"
},
{
"key": "dob",
"value": "1999-06-06"
},
{
"key": "nationality",
"value": "UK"
},
{
"key": "address",
"value": [
{
"key": "addr1",
"value": "Bundle road, near church 460102"
},
{
"key": "postalCode",
"value": "46HG02"
},
{
"key": "city",
"value": "London"
}
]
}
],
"Greeting": "Birthday",
"Service": "mydelivery"
}
使用在线工具生成模型
// MARK: - Welcome
public struct Welcome: Codable {
public let data: [Datum]
public let Greeting, Service: String
}
// MARK: - Datum
public struct Datum: Codable {
public let key: String
public let value: ValueUnion
}
public enum ValueUnion: Codable {
case string(String)
case valueElementArray([ValueElement])
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode([ValueElement].self) {
self = .valueElementArray(x)
return
}
if let x = try? container.decode(String.self) {
self = .string(x)
return
}
throw DecodingError.typeMismatch(ValueUnion.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for ValueUnion"))
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .string(let x):
try container.encode(x)
case .valueElementArray(let x):
try container.encode(x)
}
}
}
// MARK: - ValueElement
public struct ValueElement: Codable {
let key, value: String
}
尝试访问模型中的地址数组。但总是失败
print("onboardingStatus: \(result?.Greeting ?? "")")
print("idService: \(result?.Service ?? "")")
guard let userData = result?.data else { return }
for item in userData {
if item.key == "address" {
guard let address_info = item.value as? [ValueElement] else { return }
for ad in address_info {
print(ad.key)
print(ad.value)
}
}
print(item.key)
print(item.value)
}
我想遍历地址的键和值。但我收到错误“For-in 循环需要 'ValueUnion' 符合 'Sequence'”。请帮忙。
【问题讨论】:
-
我复制/粘贴了您的代码,我得到“从 'ValueUnion' 转换为不相关类型 '[ValueElement]' 总是失败”,而不是您的错误...
-
是的,我想转换为 [ValueElement] 以便循环播放。
-
您必须将您的 JSON 响应转换为您的模型对象,如下所示:- let decoder = JSONDecoder() do { let people = try decoder.decode(ModelName.self, from: result.value) print (人) } 捕捉 { 打印(error.localizedDescription) }
-
你也可以删除结构体旁边的代码......从枚举开始到结束