JSON解码失败

时间:2019-05-01 21:48:19

标签: ios json swift decodable

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

JSON信息是:

JSON response from youtube playlist info

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

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

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

正确的可分解结构为:

    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]
}

谢谢您的帮助。