问题描述
NSString * jsonString = [ [NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@jsonString:%@,jsonString);
我得到结果:
{result:\\\說}
将数据编码到正确的字符串的正确方法,而不是像\uxxxx这样的unicode字符串?
如果你转换JSON数据
{result:\\\說}
/ pre>
到
NSDictionary
(例如使用NSJSONSerialization
)并打印字典NSError *错误;
NSDictionary * jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:& error];
NSLog(@%@,jsonDict);
那么你会得到输出
{
result =\U8aaa;
}
原因是
描述
NSDictionary 的方法对所有非ASCII字符使用\Unnnn转义序列
。但是这只是在控制台中的显示,字典是正确!
如果您打印关键
NSLog(@%@,[jsonDict objectForKey:@result]);
然后你会得到预期的输出
说
NSData* jsonData is the http response contains JSON data.
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"jsonString: %@", jsonString);
I got the result:
{ "result": "\u8aaa" }
What is the proper way to encoding the data to the correct string, not unicode string like "\uxxxx"?
解决方案If you convert the JSON data
{ "result" : "\u8aaa" }
to a
NSDictionary
(e.g. usingNSJSONSerialization
) and print the dictionaryNSError *error; NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]; NSLog(@"%@", jsonDict);
then you will get the output
{ result = "\U8aaa"; }
The reason is that the
description
method ofNSDictionary
uses "\Unnnn" escape sequencesfor all non-ASCII characters. But that is only for display in the console, the dictionary is correct!If you print the value of the key
NSLog(@"%@", [jsonDict objectForKey:@"result"]);
then you will get the expected output
說
这篇关于NSData到NSString与JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!