johann
johann

Reputation: 1135

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

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

Answers (1)

JeremyP
JeremyP

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:

  • The data is not valid JSON. Try pasting it into http://jsonlint.com to see if it is OK.
  • The top level object in the JSON is an array, in which case the cast to 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

Related Questions