2

我正在查询一个将 JSON 字符串返回为NSData. 该字符串是 UTF-8 格式,所以它被转换成NSString这样的。

NSString *receivedString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]; 

但是,一些 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"}

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

谢谢,

4

1 回答 1

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);
于 2012-05-31T17:39:10.987 回答