【问题标题】:How do I exctract Json Data swift如何快速提取 Json 数据
【发布时间】:2018-11-18 04:33:32
【问题描述】:

您好,我一直在使用 youtube api,我获取了看起来像这样的 api,我已经设法通过使用解码器获取标题和描述,我的结构如下所示:

`{
kind: "youtube#videoListResponse",
etag: "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/afeay36Ls6JJ-W_ngFTxbc2s6Pw\"",
pageInfo: {
totalResults: 1,
resultsPerPage: 1
},
items: [
{
kind: "youtube#video",
etag: "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/6vv0LQwRyqqns6JEgC-Gg86wBZk\"",
id: "7lCDEYXw3mM",
snippet: {
publishedAt: "2012-06-20T23:12:38.000Z",
channelId: "UC_x5XG1OV2P6uZZ5FSM9Ttw",
title: "Google I/O 101: Q&A On Using Google APIs",
description: "Antonio Fuentes speaks to us and takes questions on working with Google APIs and OAuth 2.0.",
`

这是我的结构

struct Videos: Decodable {
            let items: [item]

        }

        struct item: Decodable {
            let snippet: snippet
        }

        struct snippet: Decodable {
            let title: String
            let description: String
            let thumbnails: thumbnails

        }

        struct thumbnails: Decodable {
            let `default`: defal
        }

        struct defal: Decodable {
            let url: String
        }

这是我获取的方法 我使用了 URLSession 我没有包含所有获取代码,因为它会太多,但是您仍然可以看到我使用 for 语句打印了标题,并且效果很好,因为在终端中我可以看到标题。

        guard let data = data else { return }
            do {
                let decoder = JSONDecoder()
                let data = try decoder.decode(Videos.self, from: data)


                for item in data.items {
                    guard let title: String = item.snippet.title else { return }

                    print(title)
                }

我希望我的单元格使用我之前声明的标题,但是当我尝试这样做时,标题突然为零,但在 fetch 块内它具有我正在寻找的值。

        print(title)
        cell.textLabel?.text = title

我的问题是如何提取标题和描述以及所有这些内容,以便以后我的单元格可以使用它,我不确定我正在使用的获取结构是否正确任何关于结构的查找反馈以及如何提取这些数据让我的手机可以使用它非常有帮助,我非常感谢

【问题讨论】:

  • 让 title = data["items"]["title"]
  • 我怀疑guard 行是否编译,因为所有对象都是非可选的。请遵守结构名称以大写字母开头的命名约定。该解决方案很可能与异步数据处理有关,然后与问题中的代码无关。

标签: ios swift swift4 fetch-api


【解决方案1】:
    struct item: Codable {

        let publishedAt: String
        let channelId: String
        let title: String
        let description: Int

        private enum CodingKeys: String, CodingKey {
            case publishedAt = "publishedAt"
            case channelId = "channelId"
            case title = "title"
            case description = "description"
        }
    }


    struct Videos: Decodable {

        let results: [item]

        private enum CodingKeys: String, CodingKey {
            case results = "items"

        }
    }

    // for parsing 
     let itemsArray =  try JSONDecoder().decode(Videos.self, from: json.rawData(options: .prettyPrinted))

 // in cell for row

let title = itemsArray[indexPath.row].title

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多