首页 > 解决方案 > 当 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] // ???
}

标签: swiftdecodable

解决方案


您需要添加CodingKeys枚举

struct MediaObject: Decodable {
    let mediaMetadata: [MediaMetadataDetails] 
    enum CodingKeys: String, CodingKey {
       case mediaMetadata = "media-metadata" 
    }
}

推荐阅读