3

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.

minorblend
  • 905
  • 1
  • 10
  • 23

1 Answers1

5

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.

warrenm
  • 31,094
  • 6
  • 92
  • 116
  • Good answer! I've just had a play running the OP's code and definitely think you are correct. The `NSData` is created identically every time and it is the creation of the `NSString` that is failing. Presumably in those cases when it works the byte beyond the end of the data just happens to be a `\0`. – mttrb Apr 24 '12 at 16:50
  • Indeed, and I suspect that in the cases where `stringWithUTF8String:` returns nil, it has seen an invalid UTF-8 byte sequence and bails, which is proper behavior. – warrenm Apr 24 '12 at 16:57
  • Sounds like a reasonable explanation. – mttrb Apr 24 '12 at 16:59