且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Objective-C:NSString不能完全从UTF-8解码

更新时间:2023-02-23 13:07:20

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