如何将NSJSONSerialization与“ñ”这样的特殊字符一起使用?

时间:2017-04-28 13:39:00

标签: ios objective-c nsjsonserialization

我正在使用NSJSONSerialization来解析Google的建议。

查询“f”会返回以下建议:

["f",["facebook","flipkart","fox news","forever 21","friv","fandango","fedex","fitbit","food near me","flights"]]

解析器工作正常但是当查询“fac”有特殊字符如“ñ”时:

["fac",["facebook","facebook search","fac","facebook app","facebook lite","facebook login","facebook logo","facebook messenger","facetime","facebook en español"]]

它抛出异常:

  

Error Domain = NSCocoaErrorDomain Code = 3840“无法将数据转换为字符139周围的字符串。” UserInfo = {NSDebugDescription =无法将数据转换为字符139周围的字符串。}

有什么想法吗?我尝试了所有不同的阅读选项,但没有一个可行。

#pragma mark -

- (void)request:(NSString *)text
{
    NSMutableArray *items = [[NSMutableArray alloc] init];

    NSString *query = [text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    NSString *languageCode = [[NSLocale preferredLanguages] firstObject];

    if (!languageCode) {

        languageCode = @"en";
    }

    NSString *URLString = [NSString stringWithFormat:@"http://suggestqueries.google.com/complete/search?q=%@&client=firefox&hl=%@", query, languageCode];

    NSError *downloadError = nil;

    NSData *JSONData = [NSData dataWithContentsOfURL:[NSURL URLWithString:URLString] options:0 error:&downloadError];

    if (!downloadError && JSONData) {

        NSError *parseError = nil;

        id object = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:&parseError];

        if (!parseError && object) {

            if ([object isKindOfClass:[NSArray class]]) {

                NSArray *objects = (NSArray *)object;

                NSArray *texts = [objects objectAtIndex:1];

                for (NSString *text in texts) {

                    SNGoogleItem *item = [[SNGoogleItem alloc] initWithText:text];

                    [items addObject:item];
                }

                [_delegate google:self didRespondWithItems:items];
            }
            else {

                [_delegate google:self didRespondWithItems:items];
            }
        }
        else {

            [_delegate google:self didRespondWithItems:items];
        }
    }
    else {

        [_delegate google:self didRespondWithItems:items];
    }
}

2 个答案:

答案 0 :(得分:1)

JSONSerialization支持JSON规范中的所有编码,Apple documentation说。

您没有提供有关数据编码方案的详细信息,但我猜您使用nonLossyASCII或类似的内容,但JSONSerialization不支持。

以下是我将数据转换为JSON的方式:

let rawString = "[[\"facebook en español\"]]"
// if I use String.Encoding.nonLossyASCII below, I get the error you are getting
let data = rawString.data(using: String.Encoding.utf8)
let dict = try! JSONSerialization.jsonObject(with: data!)
let convertedData = try! JSONSerialization.data(withJSONObject: dict)
let convertedString = String(data: convertedData, encoding: String.Encoding.utf8)!
// now convertedString contains "ñ" character

答案 1 :(得分:0)

这会将所使用的编码转换为UTF8:

NSData *JSONData = [NSData dataWithContentsOfURL:[NSURL URLWithString:URLString] options:0 error:&downloadError];

NSString *convertedJSONString; BOOL usedLossyConversion;

[NSString stringEncodingForData:JSONData encodingOptions:0 convertedString:&convertedJSONString usedLossyConversion:&usedLossyConversion];

NSData *convertedJSONData = [convertedJSONString dataUsingEncoding:NSUTF8StringEncoding];

现在,它有效!