【问题标题】:please help get data from json in swift请帮助快速从 json 获取数据
【发布时间】:2021-07-24 16:27:44
【问题描述】:

我从 json 文件中解析了数据,但我不知道如何获取这些变量。 需要字符码、名称和值。 我需要使用 swiftui 在表格中显示它们。我的控制台一团糟,我不知道如何获取这些数据

这是结构

import Foundation

struct CurrencyModel: Codable {
    let valute: [String : Valute]

    enum CodingKeys: String, CodingKey {
        case valute = "Valute"
    }
}

struct Valute: Codable {
    let charCode, name: String
    let value: Double

    enum CodingKeys: String, CodingKey {
        case charCode = "CharCode"
        case name = "Name"
        case value = "Value"
    }
}

这是解析器

class FetchDataVM: ObservableObject {
    var valueData = [String : Any]()

    init() {
        fetchCurrency()
    }

    func fetchCurrency() {
        let urlString = "https://www.cbr-xml-daily.ru/daily_json.js"
        let url = URL(string: urlString)
    
        URLSession.shared.dataTask(with: url!) {data, _, error in
            DispatchQueue.main.async {
                if let data = data {
                    do {
                        let decoder = JSONDecoder()
                        let decodedData = try decoder.decode(CurrencyModel.self, from: data)
                        print(decodedData)
                  
                    } catch {
                        print("Error! Something went wrong.")
                    }
                }
            }
        }.resume()
    }
}

【问题讨论】:

    标签: json swift dictionary parsing swiftui


    【解决方案1】:

    由于所有需要的信息都在 Valute 结构中,因此您只需要 valute 字典的值。替换

    var valueData = [String : Any]()
    

    @Published var valueData = [Valute]()
    

    print(decodedData)插入之后

    self.valueData = decodedData.valute.values.sorted{$0.name < $1.name}
    

    self.valueData = decodedData.valute.values.sorted{$0.charCode < $1.charCode}
    

    在视图中,您可以简单地使用 ForEach 表达式迭代数组

    【讨论】:

    • 同时使用属性包装器@Published for valueData 在设置属性后更新视图
    • 非常感谢!现在我将测试。你是最好的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多