Objective-C:NSString不能从UTF-8完全解码
我正在查询一个Web服务器,返回一个JSONstring作为NSData
。 该string是UTF-8格式,因此它被转换为一个NSString
像这样。
NSString *receivedString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
但是,一些UTF-8转义仍保留在输出的JSONstring中,导致我的应用程序行为不正常。 像\u2019
这样的\u2019
仍然在string中。 我试过把所有东西都删除,并用实际的字符replace它们。
我唯一能想到的就是手动replaceUTF-8转义字符的出现,但是如果有更快捷的方法,这是很多的工作!
下面是一个错误parsing的string的例子:
{"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"}
正如你所看到的,URL还没有被完全转换。
谢谢,
\u2019
语法不是UTF-8编码的一部分,它是一种特定于JSON的语法。 NSString
parsingUTF-8,而不是JSON,所以不理解它。
你应该使用NSJSONSerialization
来parsingJSON,然后从输出中取出你想要的string。
所以,例如:
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);