我正在尝试使用 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英镑"
但是,如果我运行代码,它会抛出这些错误: Error Domain=NSCocoaErrorDomain Code=3840 “操作无法完成。(Cocoa 错误 3840。)”(字符 1 周围的对象中的值没有字符串键。)UserInfo=0x7172860 {NSDebugDescription=周围的对象中的值没有字符串键字符 1。
我不知道出了什么问题..需要帮助,
另外,我试着调试了一下。看来这一行出了问题,无法以某种方式获取任何数据 -> NSData *JSONData = [[NSData alloc] initWithContentsOfURL:convertedResults];
最佳答案
您的网址格式错误。例如: http://www.google.com/ig/calculator?hl=en&q=50USD=?GBP
在浏览器中可以正常工作,因为浏览器会自动处理特殊字符,但是那呢?最后无效。
尝试使用此 URL。请务必在字符串中的 % 后面添加另一个 % 来对其进行转义。 http://www.google.com/ig/calculator?hl=en&q=50USD=%3FGBP
以下是一些其他字符编码:http://www.w3schools.com/tags/ref_urlencode.asp
关于iOS-无法获取预期的 json 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18804025/