Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does converting NSString to NSData force a trailing byte?

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.

like image 787
jpswain Avatar asked Dec 30 '12 00:12

jpswain


1 Answers

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.

like image 119
jpswain Avatar answered Oct 16 '22 12:10

jpswain