使用 JSON 问题解析阿拉伯语文本



我是Apple的JSON和Objective-c语言的新手。 我只是想做一些练习和东西

使用 yandex.ru 翻译 API

我试过这个网址

https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20170517T154730Z.927d87b76de60242.7a92e4612778a4838d40ab192df5297d2a1af4ed&text=Hello&lang=ar

正在从英语翻译成阿拉伯语(HELLO(。

在 Xcode 中的项目中,我尝试了这段代码让事情顺利进行

 NSString *jsonString = [NSString stringWithFormat:@"https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20170517T154730Z.927d87b76de60242.7a92e4612778a4838d40ab192df5297d2a1af4ed&text=Hello&lang=ar"];
jsonString = [jsonString stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSURL *url=[NSURL URLWithString:jsonString];
NSData *data=[NSData dataWithContentsOfURL:url];
NSError *error=nil;
//NSLog(@"%@",dictionary);
NSArray* dictionary = [NSJSONSerialization JSONObjectWithData:data
                                             options:kNilOptions
                                               error:&error];

NSLog(@"Your JSON Object: %@ Or Error is: %@", [dictionary valueForKey:@"text"], error);
NSString*string = [NSString stringWithFormat:@"%@",[dictionary valueForKey:@"text"]];

直到这里很好..但它在日志上返回了一个错误的值而不是(مرحبا(它的

您的 JSON 对象:( "\U0645\U0631\U062d\U0628\U0627" )

值正确。它是对象 - 一个数组 - 与NSLog一起生成显示Unicode令牌的输出。

首先,JSON对象是一个字典而不是一个数组,Objective-C编译器非常客气,此时此刻不抱怨。

NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data ...

其次,永远不要使用valueForKey从字典中获取单个对象,使用密钥订阅

NSLog(@"Your JSON Object: %@ Or Error is: %@", dictionary[@"text"], error);

但是,键text的值是一个数组。要获取结果字符串,请获取数组中的第一项,您应该检查是否没有错误以及数组是否不为空以避免超出范围的崩溃。

if (error == nil) {
    NSArray *result = dictionary[@"text"];
    if (result.count > 0) {
        NSString *string = result[0];
    }
}

现在,当您将string分配给标签或文本视图时,您将获得预期的مرحبا


PS:代码的另外两个改进:

  • 如果没有格式参数,则不需要stringWithFormat

    NSString *jsonString = @"https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20170517T154730Z.927d87b76de60242.7a92e4612778a4838d40ab192df5297d2a1af4ed&text=Hello&lang=ar";
    
  • 要转义无效字符,请使用能够以智能方式执行此操作的NSURLComponents

    NSURLComponents *components = [NSURLComponents componentsWithString:jsonString];
    NSURL *url = components.URL;
    

最新更新