gpt4 book ai didi

ios - 如果对象的键不同,如何编写模型结构

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

我正在尝试解码这些数据,但是 key 不同,所以我不确定如何设置一个可以捕获未知 key 的变量

这就是我想要实现的目标

struct Offer: Decodable {
let creationDate: Double
let description: String
let imageUrl: String
let phoneNumber: String
}

这是 JSON

{
"-Ll3YgwlwuV0AbZSwhAK": {
"creationDate": 1564518305.580168,
"description": "Hehbs",
"imageUrl": "https://firebasestorage.googleapis.com/",
"phoneNumber": "458194954"
},
"-Ll3ZWpOxPvep66qzEK6": {
"creationDate": 1564518522.191582,
"description": "Jenner",
"imageUrl": "https://firebasestorage.googleapis.com/",
"phoneNumber": "51554"
},
"-Ll3jq39mEjHS0AsycEz": {
"creationDate": 1564521488.6788402,
"description": "Jwd\t\t",
"imageUrl": "https://firebasestorage.googleapis.com/",
"phoneNumber": "dwjd"
},
"-Ll3l2u_zqi1JLrJ_049": {
"creationDate": 1564521807.552466,
"description": "like",
"imageUrl": "https://firebasestorage.googleapis.com/",
"phoneNumber": "kkef"
},
"-Ll3lSVfdKGGtMMuTcDg": {
"creationDate": 1564521912.391248,
"description": "Mmm",
"imageUrl": "https://firebasestorage.googleapis.com/",
"phoneNumber": "mm"
}
}

最佳答案

你也可以解码它:

let dictionary = try JSONDecoder().decode([String: Offer].self, from: data)

就其值(value)而言,我倾向于将 creationDate 设为 Date,将 imageUrl 设为 URL:

struct Offer: Decodable {
let creationDate: Date
let description: String
let imageUrl: URL
let phoneNumber: String
}

然后你可以解码它:

do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
let dictionary = try decoder.decode([String: Offer].self, from: data)
print(dictionary)
} catch {
print(error)
}

关于ios - 如果对象的键不同,如何编写模型结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57280761/

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