读取JSON文件后无法读取阿拉伯字母 [英] Cannot read Arabic letters after reading JSON file

查看:128
本文介绍了读取JSON文件后无法读取阿拉伯字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码读取包含数字和阿拉伯字符串的json.txt文件:

I am using this code to read a json.txt file which contains numbers and Arabic string :

if let path = Bundle.main.path(forResource: "data", ofType: "txt") {
    do {
        let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
        let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
        if let jsonResult = jsonResult as? Dictionary<String, Any>, let person = jsonResult["Sheet1"] as? [Any] {          
            print(person)
        }
    } catch {
        // handle error
    }
}

但是阿拉伯字符串的结果如下:

but the result of the Arabic string looks like that:

"Question" = "\U0648\U0644\U062f \U0627\U0644\U0646\U0628\U0649 \U0635\U0644\U0649 \U0627\U0644\U0644\U0647 \U0639\U0644\U064a\U0647 \U0648 \U0633\U0644\U0645 \U0641\U0649";
"answer 1" = "\U0627\U0644\U0645\U062f\U064a\U0646\U0647 \U0627\U0644\U0645\U0646\U0648\U0631\U0629";

有人可以帮我解决吗? 谢谢

Can anyone help me to solve it? Thanks

推荐答案

使用字符串格式时可以设置编码,因此可以使用以下代码:

you can set Encoding when you use String Format, so you can use below code:

if let path = Bundle.main.path(forResource: "data", ofType: "txt") {
    do {
          let data = try String(contentsOf: URL(fileURLWithPath: "path"), encoding: String.Encoding.utf8)
          let jsonResult = try JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: .mutableLeaves)
          if let jsonResult = jsonResult as? Dictionary<String, Any>, let person = jsonResult["Sheet1"] as? [Any] {          
               print(person)
          }
       } catch {
           // handle error
       }
}

refer链接: Apple Developer String Initializer

这篇关于读取JSON文件后无法读取阿拉伯字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆