ios - 使用 JSONDecoder Swift 解码
问题描述
下面的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)
}
推荐阅读
- php - 使用 php 从对象 json 读取数据
- python - KivyMD 对话框未调整其小部件的大小
- visual-studio-2019 - 打开任何 Razor 页面后 VS2019 崩溃;“由于内部错误,Razor Taghelper 提供程序当前不可用”
- javascript - 对象为空时如何阻止useSelector触发?
- r - 基于R中数据框中行名中的相同文本创建阶乘列
- powerbi - 使用动态表名称引用变量表 - Power BI、DAX
- java - 如何仅从 java/kotlin 数据类生成 openapi 模式?(对于基于 vert.x 的应用程序)
- c# - LDAP 查询 AD 林信任中的跨域
- material-ui - Material-UI/app-bar/#back-to-top-findDOMNode 在 StrictMode 中已弃用。findDOMNode 被传递了一个在 StrictMode 内的 Transition 实例
- edgeengine - mimik-edge-cli account get-edge-access-token 步骤出错