17

This is in response to this incorrect answer: https://stackoverflow.com/a/7894952/192819

Does converting NSString like this:

NSString *str = @"teststring";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

force a trailing \0 byte, which means

-[NSJSONSerialization:JSONObjectWithData:] 

and others will fail unless you remove it.

Community
  • 1
  • 1
jpswain
  • 14,642
  • 8
  • 58
  • 63
  • 1
    Ha! You've certainly gotten plenty of rep from what, is, essentially, an extended comment (that happened to fit nicely into a Q&A format) in response to an incorrect answer. Well, I won't begrudge you it. :) – Mark Amery Oct 10 '13 at 17:34

1 Answers1

31

No, it does not. See this example:

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                      @"v1", @"k1", 
                      @"v2", @"k2",
                      nil];
NSLog(@"dict=%@", dict);

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];    

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

NSData *jsonDataFromString = [jsonAsString dataUsingEncoding:NSUTF8StringEncoding];

// DO NOT DO THIS:
// jsonDataFromString = [jsonDataFromString subdataWithRange:NSMakeRange(0, [jsonDataFromString length] - 1)];

NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonDataFromString options:0 error:nil];
NSLog(@"jsonObject=%@", jsonObject);

Try it, and then try it with the "DO NOT DO THIS" line uncommented. You will see there is no problem.

jpswain
  • 14,642
  • 8
  • 58
  • 63
  • 2
    So nice to see people answering their own questions again. – CodaFi Dec 30 '12 at 02:01
  • 1
    @CodaFi is it a bad thing? – jpswain Jan 14 '13 at 07:13
  • 5
    No, in fact, it's encouraged under the FAQ. It's just that some people see it as cheating and start downvoting like mad when it happens. – CodaFi Jan 14 '13 at 13:40
  • 3
    I would have hoped that since I posted it specifically to correct a totally incorrect answer in another question that would not be considered a bad thing. Bummer. – jpswain Jan 15 '13 at 18:33