Swift decodable with unknown coding key and value [duplicate]

左心房为你撑大大i 提交于 2019-12-20 04:19:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!