我正在尝试使用 google currency rest api 来获取 USD->GBP 转换结果。像这样-> http://www.google.com/ig/calculator?hl=en&q=100USD=?GBP
json 的响应是:
{lhs: "100 美元",rhs: "62.9802242 英镑",error: "",icc: true}
所以我试图从存储到 2 个字符串中的“lhs”“rhs”中获取值
这是我获取转换结果数据的方法:
@implementation ConvertorBrain
-(id)initWithFromCurrency:(NSString *)fromCurrency
toCurrency:(NSString *)toCurrency
withAmount:(int)amount
{
if (self=[super init]) {
self.fromCurrency = fromCurrency;
self.toCurrency = toCurrency;
self.amount = amount;
}
return self;
}
-(void)getConvertResult
{
NSString *encodeFromCurrencyTerm = [self.fromCurrency stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *encodeToCurrencyTerm = [self.toCurrency stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *searchLocation = [NSString stringWithFormat:@"http://www.google.com/ig/calculator?hl=en&q=%d%@=?%@", self.amount, encodeFromCurrencyTerm, encodeToCurrencyTerm];
NSURL *convertedResults = [NSURL URLWithString:searchLocation];
NSData *JSONData = [[NSData alloc] initWithContentsOfURL:convertedResults];
if ([JSONData length] > 0) {
NSError *error = nil;
NSDictionary *dictoionary = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:&error];
if (!dictoionary) {
NSLog(@"Json parsing failed: %@", error);
}
self.lhs = [dictoionary valueForKey:@"lhs"];
self.rhs = [dictoionary valueForKey:@"rhs"];
} else {
[[[UIAlertView alloc] initWithTitle:@"Service Error" message:@"Cannot complete your request at this time, please try later" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
}
}
然后我在其他地方像这样调用方法:
self.brain = [[ConvertorBrain alloc] initWithFromCurrency:@"USD" toCurrency:@"GBP" withAmount:100];
[self.brain getConvertResult];
那么我预期的 lhs 和 rhs 结果应该是 lhs="100 美元" rhs="62.9802242 英镑"
但是,如果我运行代码,它会抛出这些错误:错误域 = NSCocoaErrorDomain 代码 = 3840“操作无法完成。(可可错误 3840。)”(在字符 1 周围的对象中没有值的字符串键。 ) UserInfo=0x7172860 {NSDebugDescription=对象中字符 1 周围的值没有字符串键。}
我无法弄清楚出了什么问题..需要帮助,另外,我尝试对其进行调试。似乎这条线出了问题,以某种方式获取任何数据->NSData *JSONData = [[NSData alloc] initWithContentsOfURL:convertedResults];