如何将NSDictionary转换为包含NSDictionary的
JSON的NSString?我试过但没有成功
//parameters is NSDictionary let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(data!,options:NSJSONReadingOptions.MutableContainers,error: &error) as NSDictionary
我想在swift中将这个NSDictionary Json转换为NSString
您可以使用以下代码:
原文链接:https://www.f2er.com/swift/319138.htmlvar error: NSError? var dict: NSDictionary = [ "1": 1,"2": "Two","3": false ] let data = NSJSONSerialization.dataWithJSONObject(dict,options: NSJSONWritingOptions.PrettyPrinted,error: &error) if let data = data { let json = NSString(data: data,encoding: NSUTF8StringEncoding) if let json = json { println(json) } }
给定一个NSDictionary,它被序列化为NSData,然后转换为NSString.
执行转换的代码也可以更简洁地重写为:
斯威夫特3:
do { let jsonData = try JSONSerialization.data(withJSONObject: data) if let json = String(data: data,encoding: .utf8) { print(json) } } catch { print("something went wrong with parsing json") }
原始答案:
if let data = NSJSONSerialization.dataWithJSONObject(dict,error: &error) { if let json = NSString(data: data,encoding: NSUTF8StringEncoding) { println(json) } }
请注意,为了使序列化起作用,字典必须包含有效的JSON键和值.