I'm fetching JSON objects and saving them in NSString as follows:
我正在获取JSON对象并将它们保存在NSString中,如下所示:
// fetch JSON from a Wiki article
NSError *error = nil;
NSString *responseString = [NSString stringWithContentsOfURL:myURL encoding:NSUTF8StringEncoding error:&error];
This is working in general but my responseString is full of \u####
escape characters, what I want is the corresponding UTF8 characters, e.g. \u2640
should be ♀
.
这是一般的工作,但我的responseString充满了\ u ####转义字符,我想要的是相应的UTF8字符,例如\应该是♀。
What's the easiest way to decode all escape characters in my responseString
?
解码我的responseString中所有转义字符的最简单方法是什么?
UPDATE: I read somewhere that I should try fetching the JSON with NSNonLossyASCIIStringEncoding
instead of NSUTF8StringEncoding
, but this lead to an error so I didn't get a responseString
at all with this.
更新:我读的地方,我应该尝试获取的JSON与NSNonLossyASCIIStringEncoding代替NSUTF8StringEncoding,但是这会导致错误,所以我没有得到responseString这个在所有。
The error then is:
那么错误是:
Error Domain=NSCocoaErrorDomain Code=261 "The operation couldn’t be completed. (Cocoa error 261.)"
1 个解决方案
#1
6
Don't fetch a string. Fetch data and convert is using NSJSONSerialization
:
不要获取字符串。获取数据和转换使用NSJSONSerialization:
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSJSONSerialization
handles all the quoting and escaping stuff automatically.
NSJSONSerialization自动处理所有引用和转义内容。
jsonObject
will be an NSArray
or NSDictionary
, depending on the input data.
jsonObject将是NSArray或NSDictionary,具体取决于输入数据。
Remark: dataWithContentsOfURL
blocks the current thread until the request is completely finished (or timed out). If that is an issue, consider to use one of the asynchronous methods of NSURLConnection
to fetch the data.)
备注:dataWithContentsOfURL阻塞当前线程,直到请求完全结束(或超时)。如果这是一个问题,请考虑使用NSURLConnection的异步方法之一来获取数据。)
#1
6
Don't fetch a string. Fetch data and convert is using NSJSONSerialization
:
不要获取字符串。获取数据和转换使用NSJSONSerialization:
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSJSONSerialization
handles all the quoting and escaping stuff automatically.
NSJSONSerialization自动处理所有引用和转义内容。
jsonObject
will be an NSArray
or NSDictionary
, depending on the input data.
jsonObject将是NSArray或NSDictionary,具体取决于输入数据。
Remark: dataWithContentsOfURL
blocks the current thread until the request is completely finished (or timed out). If that is an issue, consider to use one of the asynchronous methods of NSURLConnection
to fetch the data.)
备注:dataWithContentsOfURL阻塞当前线程,直到请求完全结束(或超时)。如果这是一个问题,请考虑使用NSURLConnection的异步方法之一来获取数据。)