如何在Swift(iOS,Xcode)中将NSDictionary转换为Json String?

前端之家收集整理的这篇文章主要介绍了如何在Swift(iOS,Xcode)中将NSDictionary转换为Json String?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > 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字符串?
在swift中,xcode?

无需实现这种复杂的逻辑,

你可以简单地做到这一点

var jsonData: NSData = NSJSONSerialization.dataWithJSONObject(dictionary,options: NSJSONWritingOptions.PrettyPrinted,error: &error)!
    if error == nil {
        return NSString(data: jsonData,encoding: NSUTF8StringEncoding)! as String
    }

如果你想用API发送它到服务器,甚至不需要将它转换为String

猜你在找的Swift相关文章