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

标签 objective-c ios nsstring

我正在查询一个 Web 服务器,它返回一个 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 尚未完全转换。

谢谢,

最佳答案

\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);

关于Objective-C:NSString 没有完全从 UTF-8 解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10838372/

相关文章:

ios - UIScrollView水平和垂直滚动的策略

ios - 拾取和弹出力触摸手势有时不起作用

ios - 将所有 TextField 委托(delegate)添加到 UIView 的简单方法?

ios - 清理格式错误的 UTF-8 数据

ios - UILabel 中看似不受支持的 unicode 字符

ios - 等于 : and isKindOfClass: - Which is faster?

ios - UIViewController子类策略

ios - 'SKNode ?' does not have a member named '位置'

ios - 指定字体时,NSString.boundingRect 失败并显示 "[NSNull renderingMode]: unrecognized selector sent to instance"

ios - 重写值时 for 循环出错