NSJSONSerialization and SBJson work weird

I tried converting the same NSDictionary object to NSData and then NSString using NSJSONSerialization and SBJsonWriter several times, and sometimes a different string. even null. This is rather strange, and I cannot find any reason. = (JSONKit and YAJL do not have such problems. Below 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 console output ...

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)

outputs changes every time I run the test code. the size of the data byte is the same, but the length of the string converted to UTF8 changes.

+3
source share
1 answer

The bytes in the object NSDataoptionally contain a string with a null character. If you want to convert the data to NSString, do this instead:

[[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding]

, '\ 0' , , , . , .

+5

All Articles