如何在 Swift(iOS、Xcode)中将 NSDictionary 转换为 Json 字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34326808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:24:37  来源:igfitidea点击:

How to convert NSDictionary to Json String in Swift ( iOS, Xcode )?

iosjsonswiftnsdictionary

提问by Rivu Chakraborty

I'm suffering from the following problem.... My NSDictionaryis like that :

我遇到了以下问题......我 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]
    ]
]

But If I print this,

但如果我打印这个,

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

The Out put Is like that :

输出是这样的:

{
    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;
        }
    ); }

How Can I get exact Json String? In swift, xcode?

如何获得准确的 Json 字符串?在 swift 中,xcode?

回答by Mihir Mehta

No need to implement this kind of complex logic,

不需要实现这种复杂的逻辑,

You can simply do this

你可以简单地做到这一点

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

and if you want to send it with API to server , no need to even convert it to String

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