2

I am attempting to parse JSON using Decodable that has the following structure and I am being thrown the error:

does not confirm to protocol "Decodable"

The JSON structure looks as such:

{
    base = SGD;
    date = "2017-12-29";
    rates =     {
        AUD = "0.95769";
        BGN = "1.2205";
        THB = "24.414";
        TRY = "2.8372";
        USD = "0.74844";
        ZAR = "9.2393";
    };
}

Note that I have shrank the size of the JSON object for readability.

The trouble here is that the rates are all different key-value pairs which are unlike the posts here and here. My code so far as such:

struct Fixer: Decodable {
    let base: String
    let date: String
    let rates: [AnyObject]
}

//at dataTasks
do {
     let results = try JSONDecoder().decode(Fixer.self, from: data)
     print(results.base)
} catch error as NSError {
     print(error?.localizedDescription)
}

It would be helpful if anyone could advice under such JSON structure with differing key-value pairs, how should one write the struct?

My reference: video

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Koh
  • 2,687
  • 1
  • 22
  • 62

1 Answers1

0

The value for key rates is a dictionary, not an array.

The most reasonable way is to decode the object to a dictionary

let rates: [String:String]

Alternatively create a struct Rate (for example with members currency and value) and write a custom initializer to map the dictionary (key -> currency and value -> value) to an array of Rate

Note: Consider that neither unspecified AnyObject nor Any can be used as a destination type.

vadian
  • 274,689
  • 30
  • 353
  • 361