Objective-C:NSString不能完全从UTF-8解码 [英] Objective-C: NSString not being entirely decoded from UTF-8

查看:80
本文介绍了Objective-C:NSString不能完全从UTF-8解码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查询Web服务器,该服务器返回JSON字符串作为NSData.该字符串采用UTF-8格式,因此会像这样转换为NSString.

I'm querying a web server which returns a JSON string as NSData. The string is in UTF-8 format so it is converted to an NSString like this.

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

但是,某些utf-8转义符保留在输出的JSON字符串中,这导致我的应用程序行为异常.诸如\u2019之类的内容仍保留在字符串中.我已尽一切努力将其删除,并用其实际字符替换.

However, some UTF-8 escapes remain in the outputted JSON string which causes my app to behave erratically. Things like \u2019 remain in the string. I've tried everything to remove them and replace them with their actual characters.

我唯一想到的就是用他们的角色手动替换UTF-8转义符的出现,但是如果有更快的方法,这是很多工作!

The only thing I can think of is to replace the occurances of UTF-8 escapes with their characters manually, but this is a lot of work if there's a quicker way!

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

Here's an example of an incorrectly parsed 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尚未完全转换.

As you can see, the URL hasn't been completely converted.

谢谢

推荐答案

\u2019语法不是UTF-8编码的一部分,它是JSON特定的语法. NSString解析UTF-8,而不是JSON,因此无法理解.

The \u2019 syntax isn't part of UTF-8 encoding, it's a piece of JSON-specific syntax. NSString parses UTF-8, not JSON, so doesn't understand it.

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

You should use NSJSONSerialization to parse the JSON then pull the string you want from the output of that.

例如,

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解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆