【问题标题】:keyNotFoundError while Fetching JSON data from an API in SwiftUI在 SwiftUI 中从 API 获取 JSON 数据时出现 keyNotFoundError
【发布时间】:2021-07-09 10:03:04
【问题描述】:

我最近开始学习使用 Swift 编写代码,并且一直在努力从 API 中获取数据。这是数据的样子:

{
   "status":200,
   "posts":[
      {
         "text":"djnkdnwnjdewkn",
         "date":"08/07/2012"
      },
      {
         "text":"dskndkc ksdskj n",
         "date":"08/17/2012"
      },
      {
         "text":"dkjdjincidjn",
         "date":"09/07/2012"
      }
   ]
}

这是我使用的代码:

import SwiftUI
import Foundation
import Combine

struct Post: Codable, Identifiable {
    public var id = UUID()
    public var text, date: String
}

struct Feed: Codable {
    public var status: Int
    public var posts: [Post]
}


class FetchPosts: ObservableObject {
    @Published var posts = [Post]()

    init() {
        let url = URL(string: "api goes here")!
        URLSession.shared.dataTask(with: url) {(data, response, error) in
            do {
                if let postData = data {
                    let decodedData = try JSONDecoder().decode(Feed.self, from: postData)
                    DispatchQueue.main.async {
                        self.posts = decodedData.posts
                    }
                } else {
                    print("No data")
                }
            } catch {
                print(error)
            }
        }.resume()
    }
}


struct FeedView: View {
    @ObservedObject var fetch = FetchPosts()
    var body: some View {
        ScrollView{
            VStack {
                ForEach(fetch.posts) { post in
                    VStack(alignment: .leading) {
                        Text(post.text)
                        Text("\(post.date)")
                            .font(.system(size: 11))
                            .foregroundColor(Color.gray)
                    }
                }
            }
        }
    }
}

到目前为止,我无法生成任何输出,但出现错误:

"keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "posts", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: "id", intValue: nil) ("id").", underlyingError: nil))"

任何帮助将不胜感激!

【问题讨论】:

    标签: json swift api fetch


    【解决方案1】:

    如果不是结构的所有属性都是 json 的一部分,则需要为结构定义 CodingKey 枚举并列出 json 中包含的属性

    enum CodingKeys: String, CodingKey {
        case text, data
    }
    

    【讨论】:

      【解决方案2】:

      添加CodingKeys

      struct Post: Codable, Identifiable {
          public var id = UUID()
          public var text, date: String
      
          enum CodingKeys: String, CodingKey { // add this for keys to be decoded 
             case text, date 
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-02
        • 2021-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-14
        相关资源
        最近更新 更多