Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift:如何将json解析为字典_Json_Swift - Fatal编程技术网

Swift:如何将json解析为字典

Swift:如何将json解析为字典,json,swift,Json,Swift,我将以下内容作为控制台中的json输出 { cash_machine = "0.08924368023872375488"; dishwasher = "0.06437973678112030029"; modem = "0.04461396858096122742"; monitor = "0.28455805778503417969"; nematode = "0.04982925951480865479"; screen = "0.05664

我将以下内容作为控制台中的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\u n”,“value\u n”}

试试下面的方法

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

json
中的结果是一个类型为
[String:String]
的字典。在
json
变量中似乎已经有了一个字典。实际的问题是什么?