简体   繁体   English

Swift2:读取以UTF-8编码的本地json文件

[英]Swift2 : read a local json file encoded in UTF-8

How can I read a japanese json file with the library NSJSONSerialization ? 如何使用NSJSONSerialization库读取日语json文件?

I've tried with (code with Swift2) : 我试过了(用Swift2编写代码):

let filePath = NSBundle.mainBundle().pathForResource("myfile",ofType:"json")
let optData =  NSData(contentsOfFile:filePath!)

do {
    let abc = try NSJSONSerialization.JSONObjectWithData(optData! as NSData, options: .MutableContainers) as! NSDictionary
    print("data read: \(abc)")
} catch {
    print("error: \(error)")
}

But Data in abc are unreadable. 但是abc中的数据不可读。 So my question is : how can I change the encoding of the NSData object. 所以我的问题是:如何更改NSData对象的编码。

By the way, if I convert the NSData object into NSString , japanese json is perfectly encoded : 顺便说一句,如果我将NSData对象转换为NSString ,日文json将被完美编码:

let stringData = NSString(data: optData!, encoding: NSUTF8StringEncoding)

thank you 谢谢

JSON files are always in some Unicode encoding. JSON文件始终采用某种Unicode编码。 NSJSONSerialization automatically handles all the valid possibilities (including UTF-8) and the fact that your stringData looks reasonable suggests that the encoding is not the issue. NSJSONSerialization自动处理所有有效的可能性(包括UTF-8),并且stringData看起来很合理的事实表明编码不是问题。

Looking at your code, the possibilities for something going wrong are: 查看您的代码,出现问题的可能性是:

  • The data is not valid JSON. 数据无效的JSON。 Try pasting it into http://jsonlint.com to see if it is OK. 尝试将其粘贴到http://jsonlint.com以查看是否可以。
  • The top level object in the JSON is an array, in which case the cast to NSDictionary will fail. JSON中的顶级对象是一个数组,在这种情况下,对NSDictionary将失败。 Instead of the forced cast, use if let .... as? NSDictionary 代替强制转换,使用if let .... as? NSDictionary if let .... as? NSDictionary and if that fails, try casting it to an NSArray . if let .... as? NSDictionary ,如果失败,请尝试将其强制转换为NSArray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM