xcode - JSON error in swift -
i new swift , api programming , running following error:
uncaught exception 'nsinvalidargumentexception', reason: '-[__nscfnumber length]
this line causing error:
print(json[“totalpostsbyuser”])
for more context, more complete code sample:
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)! { 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 { } } } }
i think need replace piece of code 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 mutabledictionary easy extract value key.
hope you.
Comments
Post a Comment