JSON 解码失败

Failing with the decode of JSON

我正在尝试解码 swift 中来自 youtube API 的 JSON 响应。

JSON信息为:

我做了一个Decodable结构:

// Build a model object to import the JSON data.
struct PlaylistInformation: Decodable {
    struct Items: Decodable {
        struct VideoNumber: Decodable {
            struct Snippet: Decodable {
                let title: String
            }
            let snippet: Snippet
        }
        let videoNumber: VideoNumber
    }
    let items: Items
}

尝试解码时出现错误:

            // We decode the JSON data get from the url according to the structure we declared above.
        guard let playlistInformation = try? JSONDecoder().decode(PlaylistInformation.self, from: data!) else {
            print("Error: could not decode data into struct") <-- HERE IS THE ERROR
            return
        }

        // Comparing DB Versions.
        let videoTitle = playlistInformation.items.videoNumber.snippet.title as NSString
        print(videoTitle)

我得到的错误是:

Error: could not decode data into struct

我猜它与结构中的 "items" 有关,因为它是一个数组...但我不知道如何解决它。

鉴于 items 是一个数组,您必须将其建模为数组而不是结构:

// Build a model object to import the JSON data.
struct PlaylistInformation: Decodable {
    struct Item: Decodable {
        struct Snippet: Decodable {
            let title: String
        }
        let snippet: Snippet
    }
    let items: [Item]
}

然后使用其索引访问每个项目,例如

let videoTitle = playlistInformation.items[0].snippet.title as NSString
print(videoTitle)

是的,错误来自结构中的 "items",因为它是一个数组。

正确的 Decodable 结构是:

    struct PlaylistInformation: Decodable {
    struct Items: Decodable {
        struct Snippet: Decodable {
            struct Thumbnails: Decodable {
                struct High: Decodable {
                    let url: String
                }
                let high: High
            }
            struct ResourceId: Decodable {
                let videoId: String
            }
            let publishedAt: String
            let title: String
            let thumbnails: Thumbnails
            let resourceId: ResourceId
        }
        let snippet: Snippet
    }
    let items: [Items]
}

感谢您的帮助。