我已尝试将相同的NSDictionary对象转换为NSData,然后使用NSJSONSerialization和SBJsonWriter多次转换为NSString,有时会得到不同的字符串.甚至是空的.这很奇怪,我找不到任何理由.=(JSONKit和YAJL没有这样的问题.以下是我的测试代码.
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]);
}
Run Code Online (Sandbox Code Playgroud)
和控制台输出是......
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)
Run Code Online (Sandbox Code Playgroud)
每次运行测试代码时输出都会更改.数据的字节大小相同,但UTF8转换的字符串长度不同.
NSData对象中的字节不一定包含NUL终止的字符串.如果要将数据转换为a NSString,请执行以下操作:
[[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding]
Run Code Online (Sandbox Code Playgroud)
为了安全起见,有些解析器可能会将'\ 0'写入它们返回的数据的末尾,这就解释了为什么它们的行为更可预测.但是你不应该像你所见的那样依赖那种行为.