Swift:如何将json解析为字典

时间:2018-03-28 20:49:21

标签: json swift

我在控制台

中有以下作为json输出
{
    cash_machine = "0.08924368023872375488";
    dishwasher = "0.06437973678112030029";
    modem = "0.04461396858096122742";
    monitor = "0.28455805778503417969";
    nematode = "0.04982925951480865479";
    screen = "0.05664909631013870239";
    television = "0.03846205398440361023";
}

我的代码是

let session = URLSession.shared.dataTask(with: r) { (data, response, error) in
    if let response = response {
        print(response)
    }
    if let data = data {
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: [])
            print(json)
        } catch {
            print(error)
        }
    }
    // experiment here

    // if statement ends here
} .resume()

我想知道我如何将其解析为字典:{"key1" : "value1", "key2" : "value2", "key3" : "value3", ..., "key_n", "value_n"}

1 个答案:

答案 0 :(得分:0)

沿着这些方向尝试一些事情

do {
    let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: String]
    for key in json.keys {
        print("\(key) : \(json[key])")
    }
}