与下面的json对应的数据模型是什么?
{
dog:
{
type: "dog",
logoLocation: "url1"
},
pitbull:
{
type: "pitbull",
logoLocation: "url2"
}
}这是一本字典所以我试了一下
class PhotosCollectionModel: Codable {
var photoDictionary: Dictionary<String, PhotoModel>?
}
class PhotoModel: Codable {
var type: String?
var logoLocation: String?
}但这是行不通的。有什么帮助吗?
发布于 2019-02-17 15:50:15
你需要
struct Root: Codable {
let dog, pitbull: Dog
}
struct Dog: Codable {
let type, logoLocation: String // or let logoLocation:URL
}正确的json
{
"dog":
{
"type": "dog",
"logoLocation": "url1"
},
"pitbull":
{
"type": "pitbull",
"logoLocation": "url2"
}
}用于动态
只需在解码器中使用[String:Dog]
do {
let res = try JSONDecoder().decode([String:Dog].self,from:data)
}
catch {
print(error)
}发布于 2019-02-17 15:56:37
我会跳过第一节课
class PhotoModel: Codable {
var type: String
var logoLocation: String
}然后像字典一样解码
do {
let decoder = JSONDecoder()
let result = try decoder.decode([String: PhotoModel].self, from: data)
result.forEach { (key,value) in
print("Type: \(value.type), logo: \(value.logoLocation) (key: \(key))")
}
} catch {
print(error)
}输出
类型:狗,标志: url1 (键:狗) 型号: pitbull,徽标: url2 (键: pitbull)
这两个属性实际上都是可选的,如果不是,我建议您删除?中的任何不必要的PhotoModel (我做了)
https://stackoverflow.com/questions/54734856
复制相似问题