简体   繁体   中英

Decoding JSON with varying key-value pair using Decodable

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM