15

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?

Bowdzone
  • 3,827
  • 11
  • 39
  • 52
Rivu Chakraborty
  • 1,372
  • 2
  • 12
  • 37

1 Answers1

40

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

hasan
  • 23,815
  • 10
  • 63
  • 101
Mihir Mehta
  • 13,743
  • 3
  • 64
  • 88