I have added a JSON-file to my file-system where the data is structured like this:
{ "DDD" : "3D Systems Corporation", "MMM" : "3M Company", "WBAI" : "500.com Limited", "WUBA" : "58.com Inc.", "AHC" : "A.H. Belo Corporation", "ATEN" : "A10 Networks, Inc.", "AAC" : "AAC Holdings, Inc.", "AIR" : "AAR Corp." }
my file-name is stockDict.json
and I'm trying to retrieve the data from it by using this code:
let jsonFilePath:NSString = NSBundle.mainBundle().pathForResource("stockDict", ofType: "json")!
let jsonData:NSData = NSData.dataWithContentsOfMappedFile(jsonFilePath as String) as! NSData
let error:NSError?
let json = JSON(jsonData)
println(json[0][0].string)
But all I get when it prints is nil
. What is wrong with my code?
Any suggestions would be appreciated.
SwiftyJSON is a library that helps to read and process JSON data from an API/Server. So why use SwiftyJSON? Swift by nature is strict about data types and wants the user to explicitly declare it. This becomes a problem as JSON data is usually implicit about data types.
Adding SwiftyJSON to the demo project Here's our path: Xcode > ( Xcode project name) > Targets > (Xcode project name). In the General tab, under the Frameworks and Libraries dropdown, we click on + and select Add package dependency. Then, we enter the package Git URL: https://github.com/SwiftyJSON/SwiftyJSON.git.
Did you try with
let json = JSON(data: jsonData) // Note: data: parameter name
println(json["DDD"].string)
Swift 3/4 version:
let path = Bundle.main.path(forResource: "JSON", ofType: "json")!
let jsonString = try? String(contentsOfFile: path, encoding: String.Encoding.utf8)
let json = JSON(parseJSON: jsonString!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With