Other options than NSJSONWritingPrettyPrinted?

3.6k Views Asked by At

I convert a NSDictionary to JSON NSData with the following line:

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:answers 
                                                   options:NSJSONWritingPrettyPrinted 
                                                     error:&err];

And pass it to server side, which is a PHP script. The script reads the JSON string as:

{
  "A" : "1941",
  "D" : "1699",
  "B" : "1949",
  "E" : "1823",
  "C" : "1999"
}

How can I format the JSON string as 1 line, just like below?

{"A" : "1941", "D" : "1699", "B" : "1949", "E" : "1823", "C" : "1999"}

Is there any option other than NSJSONWritingPrettyPrinted ?

2

There are 2 best solutions below

0
On BEST ANSWER

Quoth the documentation for NSJSONWritingPrettyPrinted;

If this option is not set, the most compact possible JSON representation is generated.

If you don't want to set any bits in the writing options mask, just pass zero for that parameter. (Or in Swift, an empty option-set, which looks just like an empty array: [].)

0
On

You should not use NSJSONWritingPrettyPrinted for purposes other than debugging. You can pass in options:0 (see below) to have the minified JSON.

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:answers options:0 error:&err];

To verify this, you can convert it into a string and NSLog it.

NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

There are no other options other than NSJSONWritingPrettyPrinted:

typedef NS_OPTIONS(NSUInteger, NSJSONWritingOptions) {
    NSJSONWritingPrettyPrinted = (1UL << 0)
} NS_ENUM_AVAILABLE(10_7, 5_0);