我正在获取JSON对象,并将其保存在NSString中,如下所示:
// fetch JSON from a Wiki article
NSError *error = nil;
NSString *responseString = [NSString stringWithContentsOfURL:myURL encoding:NSUTF8StringEncoding error:&error];
这通常可以正常工作,但是我的responseString充满了
\u####
转义字符,我想要的是对应的UTF8字符,例如\u2640
应该是♀
。解码我的
responseString
中所有转义字符的最简单方法是什么?更新:
我读过某个地方,我应该尝试使用
NSNonLossyASCIIStringEncoding
而不是NSUTF8StringEncoding
来获取JSON,但这会导致错误,因此我根本没有得到responseString
。然后的错误是:
Error Domain=NSCocoaErrorDomain Code=261 "The operation couldn’t be completed. (Cocoa error 261.)"
最佳答案
不要获取字符串。获取数据并使用NSJSONSerialization
进行转换:
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSJSONSerialization
自动处理所有引用和转义内容。jsonObject
将为NSArray
或NSDictionary
,具体取决于输入数据。备注:
dataWithContentsOfURL
阻止当前线程,直到请求完全完成完成(或超时)。如果这是一个问题,请考虑使用异步之一
NSURLConnection
的方法来获取数据。)
关于ios - 如何将包含\u转义字符的JSON解码为UTF8 NSString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17010188/