这个API调用解析JSON数据有什么问题?

问题描述 投票:0回答:1

这是我当前的 SWIFTUI 代码:

import SwiftUI

struct Holidays: Decodable {
    var date: String
    var localName: String
    var name: String
    var countryCode: String
}

struct HolidaysView: View {
    @State private var holidays = [Holidays]()
    
    var body: some View {
        NavigationView {
            List(holidays, id: \.name) { t in
                VStack(alignment: .leading) {
                    Text(t.date)
                        .font(.headline)
                        .foregroundColor(.cyan)
                    Text(t.name)
                        .font(.body)
                        .foregroundColor(.indigo)
                    Text(t.countryCode)
                        .font(.body)
                        .foregroundColor(.red)
                }
            }
            .navigationTitle("Holidays List")
            .task {
                await fetchHolidaysData()
            }
        }
    }
    
    func fetchHolidaysData() async {
        // create the URL
        guard let url = URL(string: "https://date.nager.at/api/v2/publicholidays/2020/US") else {
            print("THIS URL DOES NOT WORK!")
            return
        }
        
        // fetch the data
        do {
            let (data, _) = try await URLSession.shared.data(from: url)
            
            // decode that data
            if let decodedResponse = try? JSONDecoder().decode([Holidays].self, from: data) {
                holidays = decodedResponse
            }
        } catch {
            print("This data is not valid")
        }
    }
}

struct HolidaysView_Previews: PreviewProvider {
    static var previews: some View {
        HolidaysView()
    }
}

这段代码的目标是能够使用URL查看json数据。 当我单击假期列表的导航标题时,没有显示任何数据(在内容视图中)。 我尝试过其他 API 链接,例如 JSON 的 API 占位符,并且它们有效。我无法弄清楚问题或差异。我也尝试过人工智能。我不知道我做错了什么,难道我必须使用API的所有数据变量吗?或者可能是id?我使用的其他 api 都有每个数据部分的 id,所以我把

List(holidays, id: \.name) { t in      ```
as 
List(todos, id: \.id) { t in      ```
```, could this be a possible reason?
                       
swift swiftui swift-playground
1个回答
0
投票

这是我的工作示例代码,汇集了评论的建议。

struct Holidays: Identifiable, Decodable { // <-- here
    let id = UUID() // <-- here
    
    var date: String
    var localName: String
    var name: String
    var countryCode: String

    enum CodingKeys: String, CodingKey {
        case date, localName, name, countryCode  // <-- here no id
    }
}

// for testing
struct ContentView: View {
    var body: some View {
        HolidaysView()
    }
}

struct HolidaysView: View {
    @State private var holidays = [Holidays]()
    
    var body: some View {
        NavigationStack {  // <-- here
            List(holidays) { t in   // <-- here
                VStack(alignment: .leading) {
                    Text(t.date)
                        .font(.headline)
                        .foregroundColor(.cyan)
                    Text(t.name)
                        .font(.body)
                        .foregroundColor(.indigo)
                    Text(t.countryCode)
                        .font(.body)
                        .foregroundColor(.red)
                }
            }
            .navigationTitle("Holidays List")
            .task {
                await fetchHolidaysData()
            }
        }
    }
    
    func fetchHolidaysData() async {
        // create the URL
        guard let url = URL(string: "https://date.nager.at/api/v2/publicholidays/2020/US") else {
            print("THIS URL DOES NOT WORK!")
            return
        }
        // fetch the data
        do {
            let (data, _) = try await URLSession.shared.data(from: url)
            // decode that data
            holidays = try JSONDecoder().decode([Holidays].self, from: data) // <-- here
        } catch {
            print("error: \(error)") // <-- here
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.