0

USD->GBP 変換結果を取得するために、google currency rest api を使用しようとしています。このようなもの-> http://www.google.com/ig/calculator?hl=en&q=100USD=?GBP

json の応答は次のとおりです:
{lhs: "100 US ドル",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 US ドル" rhs ="62.9802242 英国ポンド" になるはずです

ただし、コードを実行すると、次のエラーが返されます: Error Domain=NSCocoaErrorDomain Code=3840 "The operation could't be completed. (Cocoa error 3840.)" (文字 1 周辺のオブジェクトの値に文字列キーがありません。 ) UserInfo=0x7172860 {NSDebugDescription=文字 1 の周りのオブジェクトに値の文字列キーがありません。}

何がうまくいかなかったのかわかりません。助けが必要です。また、少しデバッグしようとしました。この行が間違っていたようです。どうにかしてデータを取得していません ->NSData *JSONData = [[NSData alloc] initWithContentsOfURL:convertedResults];

4

2 に答える 2

1

URL の形式が正しくないようです。例: 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

于 2013-09-14T17:03:57.520 に答える
0

json の形式が正しくない可能性があります。これを使用して、json が正しくフォーマットされていることを確認します。http://jsonlint.com/

于 2015-07-14T00:32:55.523 に答える