如何在swift中打印NSDictionary时打印中文而不是unicode

时间:2018-04-13 11:42:05

标签: ios swift

当我打印一个包含中文的NSDictionary时,Xcode控制台打印unicode,如何将unicode转换为中文?

1 个答案:

答案 0 :(得分:0)

尝试此解决方案

extension Dictionary {

    var json: String {
        let errorJson = "JSON Format error "
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
            return String(bytes: jsonData, encoding: String.Encoding.utf8) ?? errorJson
        } catch {
            return errorJson
        }
    }


}

使用代码

let dictionary = ["name":"ahmad","age":"22","gender":"male"]

print(dictionary.json)

日志结果:

{
"name":"ahmad",
"age":"22",
"gender":"male"
}