Swift2:读取以 UTF-8 编码的本地 json 文件
Swift2 : read a local json file encoded in UTF-8
如何使用 NSJSONSerialization
库读取日文 json 文件?
我试过(使用 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)")
}
但 abc 中的数据不可读。所以我的问题是:如何更改 NSData 对象的编码。
顺便说一句,如果我将 NSData
对象转换为 NSString
,那么日语 json 将得到完美编码:
let stringData = NSString(data: optData!, encoding: NSUTF8StringEncoding)
谢谢
JSON 文件总是采用某种 Unicode 编码。 NSJSONSerialization
自动处理所有有效的可能性(包括 UTF-8),而且您的 stringData
看起来合理这一事实表明编码不是问题。
查看您的代码,出现问题的可能性是:
- 数据无效JSON。尝试将其粘贴到 http://jsonlint.com 中,看看是否可以。
- JSON 中的顶级对象是一个数组,在这种情况下转换为
NSDictionary
将失败。使用 if let .... as? NSDictionary
而不是强制转换,如果失败,请尝试将其转换为 NSArray
。
如何使用 NSJSONSerialization
库读取日文 json 文件?
我试过(使用 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)")
}
但 abc 中的数据不可读。所以我的问题是:如何更改 NSData 对象的编码。
顺便说一句,如果我将 NSData
对象转换为 NSString
,那么日语 json 将得到完美编码:
let stringData = NSString(data: optData!, encoding: NSUTF8StringEncoding)
谢谢
JSON 文件总是采用某种 Unicode 编码。 NSJSONSerialization
自动处理所有有效的可能性(包括 UTF-8),而且您的 stringData
看起来合理这一事实表明编码不是问题。
查看您的代码,出现问题的可能性是:
- 数据无效JSON。尝试将其粘贴到 http://jsonlint.com 中,看看是否可以。
- JSON 中的顶级对象是一个数组,在这种情况下转换为
NSDictionary
将失败。使用if let .... as? NSDictionary
而不是强制转换,如果失败,请尝试将其转换为NSArray
。