SwiftNewbie SwiftNewbie - 5 months ago 13x
Swift Question

JSON error in swift

I am new to swift and API programming and am running into following error on a piece of code that had been working ok until recently.

Following is the error:

uncaught exception 'NSInvalidArgumentException', reason:
'-[__NSCFNumber length]

Following is the line which is specifically giving this error:


Any help and hints will be much appreciated! Thanks!

let jsonStr = NSString(data: request.HTTPBody!, encoding: NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
let httpResponse = response as? NSHTTPURLResponse
var err: NSError?

if httpResponse!.statusCode == 201 {
if error == nil {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
let jsonData: NSData = jsonStr!.dataUsingEncoding(NSUTF8StringEncoding)!
do {
if let json: AnyObject = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) {
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
totalPostsByUser = (json["totalPostsByUser"] as? Int)!
} catch let parseError {


I think you need to replace some piece of code with below code,

if let json: NSMutableDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) as? NSMutableDictionary
               let responseString = NSString(data: data!, encoding:  NSUTF8StringEncoding)
               //totalPostsByUser = (json["totalPostsByUser"] as? Int)!

Convert anyObject to MutableDictionary which will be easy to extract value from key.

Hope this will help you.