如何在Swift中使用未知密钥解码JSON响应? [英] How can I decode a JSON response with an unknown key in Swift?

查看:106
本文介绍了如何在Swift中使用未知密钥解码JSON响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拆分 https://blockchain.info/ticker ,以便每一行都是自己的数组中的字符串.

Im wanting to split up https://blockchain.info/ticker so that each line is its own string in an array.

我正在制作一个获取所选货币价格的应用程序.因此,如果有人想要AUD,那么它将获得数组中的2字符串,然后显示最后一个标签中的价格.

Im making an app that get the price of the selected currency. So if someone wants AUD then it will get the 2 string in the array and then show the price which is in the last tag.

我目前只能下载json.

I currently just have it downloading the json..

func reloadJson(){

    if globalVariables.currencySelected == "" {
        globalVariables.currencySelected = globalVariables.currencySelected + "AUD"
    }
    print(globalVariables.currencySelected)

    if let blockchainTickerURL = URL(string: "https://blockchain.info/ticker") {

        let request = NSMutableURLRequest(url: blockchainTickerURL)
        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in
            var message = ""

            if error != nil {
                print("error")
            } else {
                if let unwrappedData = data {
                    let dataString = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)

那只是我当前所拥有内容的副本和粘贴,其格式不正确.

Thats just a copy and paste of what I currently have, its not exactly formatted right.

谢谢

推荐答案

您应该看一下Swift4 Codable协议.

You should take a look at Swift4 Codable protocol.

为货币词典值创建一个结构,该结构符合Codable的相应属性:

Create a structure for the currency dictionary values that conforms to Codable with the corresponding properties:

struct Currency: Codable {
    let fifteenM: Double
    let last: Double
    let buy: Double
    let sell: Double
    let symbol: String
    private enum CodingKeys: String, CodingKey {
        case fifteenM = "15m", last, buy, sell, symbol
    }
}

要解码JSON数据,您需要使用JSONDecoder传递带有自定义值[String: Currency]的字典作为要解码的类型:

To decode your JSON data you need to use JSONDecoder passing the dictionary with custom values [String: Currency] as the type to be decoded:

let url = URL(string: "https://blockchain.info/ticker")!
URLSession.shared.dataTask(with: url) { data, response, error in
    guard let data = data else { return }
    do {
        let currencies = try JSONDecoder().decode([String: Currency].self, from: data)
        if let usd = currencies["USD"] {
            print("USD - 15m:", usd.fifteenM)
            print("USD - last:", usd.last)
            print("USD - buy:", usd.buy)
            print("USD - sell:", usd.sell)
            print("USD - symbol:", usd.symbol)
        }
    } catch { print(error) }

}.resume()


这将打印


This will print

USD-1500万:11694.03

USD - 15m: 11694.03

美元-最后一次:11694.03

USD - last: 11694.03

美元-买入:11695.01

USD - buy: 11695.01

美元-卖出:11693.04

USD - sell: 11693.04

美元-符号:$

这篇关于如何在Swift中使用未知密钥解码JSON响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆