1. convert jsonstring to dictionary
jsonstring conversion to Dictionary func getdictionaryfromjsonstring (jsonstring:string)->nsdictionary{let jsondata:d ATA = Jsonstring.data (using:. UTF8)! Let dict = try? Jsonserialization.jsonobject (With:jsondata, Options:. mutablecontainers) if dict! = nil { return dict as! Nsdictionary } return Nsdictionary () }
2.jsonstring convert to an array
Func getarrayfromjsonstring (jsonstring:string)->nsarray{let jsondata:data = Jsonstring.data (using:. UTF8)! Let array = try? Jsonserialization.jsonobject (With:jsondata, Options:. mutablecontainers) if array! = Nil { return array as! Nsarray } return array as! Nsarray }
3. Convert Dictionary to Jsonstring
/** Dictionary converted to jsonstring -parameter dictionary: Dictionary parameter -returns:jsonstring */ func Getjsonstringfromdictionary (dictionary:nsdictionary), String { if (! Jsonserialization.isvalidjsonobject (dictionary) { print ("Cannot resolve jsonstring") return ""} Let data: nsdata! = try? Jsonserialization.data (Withjsonobject:dictionary, Options: []) as nsdata! Let jsonstring = NSString (data:data as Data,encoding:string.encoding.utf8.rawvalue) return jsonstring! as String< c12/>}
Swift JSON strings and dictionaries and arrays of reciprocal