Question

I have a REST API which expects a file size field to be in bytes. However I am observing that NSJSONSerialization is converting my value to an exponential representation which my server doesn't support.

For example:

unsigned long long fileSize = 100000000000;
NSDictionary *myObject = @{"fileSize": @(fileSize)};
NSData *dataToSend = [NSJSONSerialization dataWithJSONObject:myObject options:0 error:nil];
// send dataToSend to network

On the wire I observe the following is sent:

{ "fileSize" : 1.0e+11 }

Is there any way to force NSJSONSerialization to retain the unsigned long long formatting on the wire?

E.g.

{ "fileSize" : 100000000000 }

Update: Corrected my sample code thanks to Gabriele Petronella

Was it helpful?

Solution

Turns out I was able to solve this just now by explicitly initializing the NSNumber as an unsigned long long.

E.g.

unsigned long long fileSize = 100000000000;
NSDictionary *myObject = @{"fileSize": [NSNumber numberWithUnsignedLongLong:fileSize]};
NSData *dataToSend = [NSJSONSerialization dataWithJSONObject:myObject options:0 error:nil];
// send dataToSend to network

This resulted in the output I expected:

{ "fileSize" : 100000000000 }

OTHER TIPS

I don't see any NSJSONSerialization in your question, anyway converting the dictionary to a NSData instance seems wrong, and it's likely to be causing this encoding issue. Just do something like

NSDictionary *myObject = @{"fileSize": @(fileSize)};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myObject options:0 error:nil];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top