当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何在Swift(iOS,Xcode)中将NSDictionary转换为JsonString?》经验,为你挑选了1个好方法。

我遇到了以下问题....我 NSDictionary是这样的:

var dic : NSDictionary = [ "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]
    ]
]

但如果我打印这个,

print(dic);  or print(“\(dic)”);

Out put是这样的:

{
    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?



1> Mihir Mehta..:

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

你可以这么做

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

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

推荐阅读
mobiledu2402852413
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有