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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With