Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

arrays - How can I decode a JSON response with an unknown key in Swift?

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

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.

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.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should take a look at Swift4 Codable protocol.

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
    }
}

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 - 15m: 11694.03

USD - last: 11694.03

USD - buy: 11695.01

USD - sell: 11693.04

USD - symbol: $


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...