首页 > 解决方案 > JSON解码失败

问题描述

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

JSON信息是:

来自 youtube 播放列表信息的 JSON 响应

我做了一个可解码的结构:

// 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

我想它与结构中的“项目”有关,因为它是一个数组......但我不知道如何解决这个问题。

标签: iosjsonswiftdecodable

解决方案


鉴于这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)

推荐阅读