Objective-C:NSString没有完全从UTF-8解码

Max*_*olf 2 objective-c nsstring ios

我正在查询一个返回JSON字符串的Web服务器NSData.该字符串采用UTF-8格式,因此将其转换NSString为此类型.

NSString *receivedString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]; 
Run Code Online (Sandbox Code Playgroud)

但是,一些UTF-8转义仍保留在输出的JSON字符串中,这导致我的应用程序行为不规律.类似的东西\u2019留在字符串中.我已经尝试了一切来删除它们并用它们的实际字符替换它们.

我唯一能想到的是用手动替换UTF-8逃逸的出现,但如果有更快的方法,这是很多工作!

这是一个错误解析的字符串的示例:

{"title":"The Concept, Framed, The Enquiry, Delilah\u2019s Number 10  ","url":"http://livebrum.co.uk/2012/05/31/the-concept-framed-the-enquiry-delilah\u2019s-number-10","date_range":"31 May 2012","description":"","venue":{"title":"O2 Academy 3 ","url":"http://livebrum.co.uk/venues/o2-academy-3"}
Run Code Online (Sandbox Code Playgroud)

如您所见,URL尚未完全转换.

谢谢,

Tom*_*mmy 7

\u2019语法不是UTF-8编码的一部分,它是一个特定片JSON-语法.NSString解析UTF-8,而不是JSON,所以不理解它.

您应该使用NSJSONSerialization解析JSON,然后从输出中提取所需的字符串.

所以,例如:

NSError *error = nil;
id rootObject = [NSJSONSerialization
                      JSONObjectWithData:receivedData
                      options:0
                      error:&error];

if(error)
{
    // error path here
}

// really you'd validate this properly, but this is just
// an example so I'm going to assume:
//
//    (1) the root object is a dictionary;
//    (2) it has a string in it named 'url'
//
// (technically this code will work not matter what the type
// of the url object as written, but if you carry forward assuming
// a string then you could be in trouble)

NSDictionary *rootDictionary = rootObject;
NSString *url = [rootDictionary objectForKey:@"url"];

NSLog(@"URL was: %@", url);
Run Code Online (Sandbox Code Playgroud)