JSON SWIFT, как получить доступ к значениям - PullRequest
0 голосов
/ 25 октября 2019

У меня есть следующий Json

USD {
    "avg_12h" = "8252.96";
    "avg_1h" = "8420.80";
    "avg_24h" = "8253.11";
    "avg_6h" = "8250.76";
    rates =     {
        last = "8635.50";
    };
    "volume_btc" = "76.05988903";
}

, где USD - это ключ, найденный после поиска в файле json, я хочу получить доступ к значению "avg_12h" и присвоить его переменной, что является лучшим способомсделать это.


import UIKit

/*URLSessionConfiguration.default
URLSessionConfiguration.ephemeral
URLSessionConfiguration.background(withIdentifier: <#T##String#>)

// create a URLSession instance
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)*/

/*create a URLSession instance*/
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
/*
The session.dataTask(with: url) method will perform a GET request to the url specified and its completion block
 ({ data, response, error in }) will be executed once response is received from the server.*/
let url = URL(string: "https://localbitcoins.com/bitcoinaverage/ticker-all-currencies")!
let task = session.dataTask(with: url) { data, response, error in

    // ensure there is no error for this HTTP response
    guard error == nil else {
        print ("error: \(error!)")
        return
    }

    // ensure there is data returned from this HTTP response
    guard let content = data else {
        print("No data")
        return
    }
    /*JSONSerialization.jsonObject(with: content,
     options: JSONSerialization.ReadingOptions.mutableContainers) as?
     [String: Any] will parse the JSON data returned from web server into a dictionary*/
    // serialise the data / NSData object into Dictionary [String : Any]
    guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] else {
        print("Not containing JSON")
        return
    }
    let bolivares = "VES"
    for (key, value) in json {
        if key==bolivares {
           print(value)
        //ADD CODE TO ACCESS avg_12h and assign it to a value
                }
            }
        }
    // update UI using the response here
// execute the HTTP request
task.resume()

Ответы [ 3 ]

0 голосов
/ 25 октября 2019

Попробуйте использовать CodingKey, он будет более понятным и метод JSONDecoder (). Decode. Я предполагаю, что вы используете любой JsonViewer

0 голосов
/ 27 октября 2019

Создайте две простые структуры для хранения ваших данных (я не добавил здесь все поля)

struct PriceInfo {
    let avg12h: String
    let avg1h: String
    let rates: [Rate]
}

struct Rate {
    let last: String
}

, затем после преобразования json вы можете отобразить его в словарь [String: PriceInfo], где ключэто код валюты

do {
    if let json = try JSONSerialization.jsonObject(with: content) as? [String: Any] {
        let prices: [String: PriceInfo] = json.mapValues {
            let dict = $0 as? [String: Any]
            let avg12h = dict?["avg_12h"] as? String ?? ""
            let avg1h = dict?["avg_1h"] as? String ?? ""
            let rates = dict?["rates"] as? [String: String] ?? [:]
            return PriceInfo(avg12h: avg12h, avg1h: avg1h, rates: rates.compactMap { rate in Rate(last: rate.value) } )
        }
    }
} catch {
    print(error)
    return
}
0 голосов
/ 25 октября 2019

Предполагая, что вы получаете JSON в виде необработанных данных, и он еще не был преобразован в объект, вы захотите сделать что-то вроде следующего:

guard let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as! [String:[String]] else { return }
let usd = jsonObject["USD"]
let avg_12h = usd["avg_12h"]

Но это будет работать только на основенекоторые предположения, которые я сделал относительно JSON, который вы предоставили. Есть ли способ связать вставку полного файла JSON?

...