Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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?

like image 228
Rivu Chakraborty Avatar asked Dec 17 '15 04:12

Rivu Chakraborty


1 Answers

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

like image 148
Mihir Mehta Avatar answered Oct 02 '22 23:10

Mihir Mehta