swift - 当 JSON 的名称中包含带有“-”的字符串时,如何使用 Decodable 解析 JSON
问题描述
所以我尝试使用 Decodable 进行 JSON 解析,并且 Decodable 结构的字段应该与它们在 JSON 中的名称匹配,但是 JSON 中有一个对象,其名称中有一个“-”。如何命名结构中的字段?
JSON:
"media-metadata": [
{
"format": "Standard Thumbnail",
"height": 75,
"width": 75
},
{
"format": "mediumThreeByTwo440",
"height": 293,
"width": 440
}
]
代码:
struct MediaMetadataDetails: Decodable {
let format: String
let height: Int
let width: Int
}
struct MediaObject: Decodable {
let media-metadata: [MediaMetadataDetails] // ???
}
解决方案
您需要添加CodingKeys
枚举
struct MediaObject: Decodable {
let mediaMetadata: [MediaMetadataDetails]
enum CodingKeys: String, CodingKey {
case mediaMetadata = "media-metadata"
}
}
推荐阅读
- java - 使用保存方法而不是 saveIncremental 使用 PDFBox 进行 PDF 签名
- scala - Spark - 写入 128 MB 大小的 parquet 文件
- python - 从数组中按一定顺序获取固定数量的数据
- python - 如何使用 Python 将特定选定行拆分为多行
- javascript - Apify - 如何在数据集中包含失败的结果
- search - 你能搜索整个 Youtube 成绩单内容吗?
- typescript - 为什么打字稿编译器允许这样做?
- visual-studio-code - Pub 在 VS Code 中不可访问,但在 CMD 中可访问
- sql - 为什么 SELECT 在死锁图中显示更新锁
- ios - 在 module.modulemap 中找不到头文件