Reputation: 1135
How can I read a japanese json file with the library NSJSONSerialization
?
I've tried with (code with 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. So my question is : how can I change the encoding of the NSData object.
By the way, if I convert the NSData
object into NSString
, japanese json is perfectly encoded :
let stringData = NSString(data: optData!, encoding: NSUTF8StringEncoding)
thank you
Upvotes: 1
Views: 1117
Reputation: 86661
JSON files are always in some Unicode encoding. 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.
Looking at your code, the possibilities for something going wrong are:
NSDictionary
will fail. Instead of the forced cast, use if let .... as? NSDictionary
and if that fails, try casting it to an NSArray
. Upvotes: 2