Djirro
Djirro

Reputation: 318

please help get data from json in swift

I parsed data from a json file, but I don't know how to get these variables. Need charcode, name and value. enter image description here I need to display them in a table using swiftui. I got a mess in the console and I don't know how to get to this data enter image description here

this is struct

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

and this is parser

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()
    }
}

Upvotes: 1

Views: 104

Answers (1)

vadian
vadian

Reputation: 285064

As all needed information is in the Valute struct you need only the values of the valute dictionary. Replace

var valueData = [String : Any]()

with

@Published var valueData = [Valute]()

and after the line print(decodedData) insert

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

or

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

In the view you can iterate the array simply with a ForEach expression

Upvotes: 1

Related Questions