问题
I want to decode the following object from the server
{"USD":6385.74,"JPY":715249.73,"EUR":5582.36}
but I want to use a decodable struct with unknown key and value.Is this possible?
Regards,
Spyros
回答1:
You can try
let res = try? JSONDecoder().decode([String:Double].self,from:data)
print(res["USD"])
which will enable you to decode any key
回答2:
When I work with JSONs that are not fully known (as in I know all the possible keys and need all of them) I used SwiftyJSON library: https://github.com/SwiftyJSON/SwiftyJSON
It's much easier to work with than the built in JSON decoder
in your case it would be:
var jsonString = "{\"USD\":6385.74,\"JPY\":715249.73,\"EUR\":5582.36}"
let json = JSON(parseJSON: jsonString)
then you can do a bunch of stuff like iterating over keys
for (key, value) in json {
if let currency = key.string {
print (currency,value)
}
}
Check out the documentation in https://github.com/SwiftyJSON/SwiftyJSON
来源:https://stackoverflow.com/questions/53140765/swift-decodable-with-unknown-coding-key-and-value