如何在Swift(iOS,Xcode)中将NSDictionary转换为Json String?
发布时间:2020-12-14 05:33:47 所属栏目:百科 来源:网络整理
导读:参见英文答案 Convert Dictionary to JSON in Swift8个 我遇到了以下问题…. 我的NSDictionary是这样的: var dic : NSDictionary = [ "level" : [ ["column" : 0,"down" : 0,"left" : 0,"right" : 0,"row" : 0,"up" : 0],["column" : 1,["column" : 2,["col
参见英文答案 >
Convert Dictionary to JSON in Swift8个
我遇到了以下问题…. 我的NSDictionary是这样的: var dic : NSDictionary = [ "level" : [ ["column" : 0,"down" : 0,"left" : 0,"right" : 0,"row" : 0,"up" : 0],["column" : 1,["column" : 2,["column" : 0,"row" : 1,"up" : 0] ] ] 但如果我打印这个, print(dic); or print(“(dic)”); 输出是这样的: { level = ( { column = 0; down = 0; left = 0; right = 0; row = 0; up = 0; },{ column = 1; down = 0; left = 0; right = 0; row = 0; up = 0; },{ column = 2; down = 0; left = 0; right = 0; row = 0; up = 0; },{ column = 0; down = 0; left = 0; right = 0; row = 1; up = 0; },{ column = 1; down = 0; left = 0; right = 0; row = 1; up = 0; },{ column = 2; down = 0; left = 0; right = 0; row = 1; up = 0; } ); } 我怎样才能得到精确的Json字符串?
无需实现这种复杂的逻辑, 你可以简单地做到这一点 var jsonData: NSData = NSJSONSerialization.dataWithJSONObject(dictionary,options: NSJSONWritingOptions.PrettyPrinted,error: &error)! if error == nil { return NSString(data: jsonData,encoding: NSUTF8StringEncoding)! as String } 如果你想用API发送它到服务器,甚至不需要将它转换为String (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |