gpt4 book ai didi

ios - 使用 JSONDecoder Swift 解码

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

下面的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?
}

但它不起作用。有什么帮助吗?

最佳答案

你需要

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)
}

关于ios - 使用 JSONDecoder Swift 解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54734856/

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