SwiftNewbie SwiftNewbie - 6 months ago 18
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:

print(json[“totalPostsByUser”])


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)
print(responseString)
print(json["totalPostsByUser"])
totalPostsByUser = (json["totalPostsByUser"] as? Int)!
}
} catch let parseError {
}
}
}

Answer

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)
               print(responseString)
               //print(json["totalPostsByUser"])
               print(json.valueForKey("totalPostsByUser"))
               //totalPostsByUser = (json["totalPostsByUser"] as? Int)!
    }

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

Hope this will help you.

Comments