[英]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: 查看您的代码,出现问题的可能性是:
NSDictionary
will fail. 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.