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