-2

I have json as below.

{
  "CHF": 1.0064,
  "KZT": 0.0027,
  "ZAR": 0.0676,
  "INR": 0.0136,
  "CNY": 0.1456,
  "UZS": 0.0001,
  "AUD": 0.7062,
  "KRW": 0.0009
}

This is nothing but list of currency & their rates.

I am confused how to parse this data.

Usually I was creating Model to parse the json data as below for User data (& not for above case).

struct UserData : Decodable {
    var firstName : String?
    var lastName : String?
}

& while parsing I have as below.

let globalErrObj = try JSONDecoder().decode(UserData.self, from: data!)

However as this is key value data, I am confused how Model & parsing would be.

Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
  • Is this the whole JSON? to parse this you need to use a Dictionary, `[String: Decimal]` – Scriptable Oct 08 '18 at 08:06
  • 1
    How does `"CHF": 1.0064` relate to `firstName, lastName`? – Ashley Mills Oct 08 '18 at 08:08
  • This JSON will be parsed to a Dictionary of String keys and Double values. If you want something like array of objects from this dictionary where object is as struct which contains currencyName and value as properties, you have to do it yourself. – Puneet Sharma Oct 08 '18 at 08:13
  • @AshleyMills : Updated question... I show that as sample for parsing user data... – Fahim Parkar Oct 08 '18 at 08:17

1 Answers1

4

My suggestion is to decode the JSON as [String:Double] and map it to an array of a custom struct

struct Rate {
    let name : String
    let value : Double
}


let rates = try JSONDecoder().decode([String: Double].self, from: data!).map(Rate.init)
vadian
  • 274,689
  • 30
  • 353
  • 361