Friday, 15 April 2011

json - NSJSONSeralization.dataWithJSONObject crashing -



json - NSJSONSeralization.dataWithJSONObject crashing -

i have problem nsjsonseralization.datawithjsonobject.

this create application crash:

@ibaction func sendmessage(sender: anyobject) { cachedmessage = messagefield.text messagefield.text = "" allow messagedata = nsjsonserialization.datawithjsonobject(cachedmessage, options: nsjsonwritingoptions.prettyprinted, error: nil) ... }

i hope can somehow help me...

it give error : invalid top-level type in json write

if trying create json object should either array or dictionary. because object want convert in json must top level object.

the top level object nsarray or nsdictionary.

try in way :

var demoarray : nsarray! // (use if want send info array) var demodic : nsdictionary! // (use if want send info dictionary (key - value pair)) var cachedmessage : string! cachedmessage = "sample" // here string textfield demoarray = [cachedmessage] // array string object demodic = ["your key":cachedmessage] // dic string object.

you can provide desired key instead of key

this how can create info array , dictionary.

allow msgdataofarray = nsjsonserialization.datawithjsonobject(demoarray, options: nsjsonwritingoptions.prettyprinted, error:nil) allow msgdataofdic = nsjsonserialization.datawithjsonobject(demodic, options: nsjsonwritingoptions.prettyprinted, error: nil)

if want see how info after jsonserialization process can see below way

var datatostringforarray = nsstring(data: msgdataofarray!, encoding: nsutf8stringencoding) var datatostringfordic = nsstring(data: msgdataofdic!, encoding: nsutf8stringencoding) println("data string of array : \(datatostringforarray)") println("data string of dic : \(datatostringfordic)")

json xcode swift ios8

No comments:

Post a Comment