I've tried converting the same NSDictionary object into NSData and then NSString using NSJSONSerialization and SBJsonWriter several times, and sometimes got a different string. even null. It's quite weird and I can't find any reason. =( JSONKit and YAJL don't have problems like this. Following is my test code.
for (int i = 0; i < 5; i++) {
NSDictionary *d = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
NSData *data = [NSJSONSerialization dataWithJSONObject:d options:0 error:nil];
NSLog(@"%@", [NSString stringWithUTF8String:data.bytes]);
}
and the console output is ...
2012-04-25 01:35:33.113 Test[19347:c07] {"key":"value"}
2012-04-25 01:35:33.114 Test[19347:c07] (null)
2012-04-25 01:35:33.114 Test[19347:c07] {"key":"value"}
2012-04-25 01:35:33.114 Test[19347:c07] {"key":"value"}
2012-04-25 01:35:33.115 Test[19347:c07] (null)
output changes every time I run the test code. data's byte size is the same, but UTF8-converted string length varies.
The bytes in an NSData
object do not necessarily comprise a NUL-terminated string. If you want to convert the data into an NSString
, do this instead:
[[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding]
There's a possibility that some parsers write '\0' to the end of the data they return for safety, which explains why they behave more predictably. But you shouldn't rely on that behavior, as you've seen.