Yahoo stock symbol suggest lookup is not json 格式!无法解析

Yahoo stock symbol suggest lookup is not json format! Unable to parse

我的目的是制作一个应用程序 (iOS),用户可以在其中输入任意字母组合,yahoo 会推荐几只最接近该搜索的股票。

我的问题实际上与一个较旧的问题有关,在这里: Stock ticker symbol lookup API

并通过这样做回答: http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=k&callback=YAHOO.Finance.SymbolSuggest.ssCallback

你明白了:

YAHOO.Finance.SymbolSuggest.ssCallback({"ResultSet":{"Query":"k","Result":[{"symbol":"K","name":"Kellogg Company","exch":"NYQ","type":"S","exchDisp":"NYSE","typeDisp":"Equity"},{"symbol":"KO","name":"The Coca-Cola Company","exch":"NYQ","type":"S","exchDisp":"NYSE","typeDisp":"Equity"},{"symbol":"KRA","name":"Kraton Performance Polymers Inc.","exch":"NYQ","type":"S","exchDisp":"NYSE","typeDisp":"Equity"},{"symbol":"KMI","name":"Kinder Morgan, Inc.","exch":"NYQ","type":"S","exchDisp":"NYSE","typeDisp":"Equity"},{"symbol":"KEY","name":"KeyCorp.","exch":"NYQ","type":"S","exchDisp":"NYSE","typeDisp":"Equity"},{"symbol":"KMB","name":"Kimberly-Clark Corporation","exch":"NYQ","type":"S","exchDisp":"NYSE","typeDisp":"Equity"},{"symbol":"KRFT","name":"Kraft Foods Group, Inc.","exch":"NMS","type":"S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"KORS","name":"Michael Kors Holdings Limited","exch":"NYQ","type":"S","exchDisp":"NYSE","typeDisp":"Equity"},{"symbol":"GMCR","name":"Keurig Green Mountain, Inc.","exch":"NMS","type":"S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"KLAC","name":"KLA-Tencor Corporation","exch":"NMS","type":"S","exchDisp":"NASDAQ","typeDisp":"Equity"}]}})

但这不是有效的 JSON 格式。返回数据的第一部分为:

YAHOO.Finance.SymbolSuggest.ssCallback(

我不知道该怎么办。当我这样做时:

NSDictionary *root = [NSJSONSerialization JSONObjectWithData: data
options:NSJSONReadingAllowFragments error: &parsingError];
NSLog(@"root: %@", root);

根为空。在一个普通的 json 对象中,我使用 options:kNilOptions 但在尝试 google 解决方案后改变了。

错误信息是这样的:

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x7ff5637375f0 {NSDebugDescription=Invalid value around character 0.}

我该怎么办?请明确。我真的 google 很生气,但我不明白。谢谢!

我的完整代码是:

- (void)createSearchObj: (NSString*)searchStr {

NSString *searchString = [NSString stringWithFormat: @"http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=%@&callback=YAHOO.Finance.SymbolSuggest.ssCallback", searchStr];

NSLog(@"searchString: %@", searchString);

NSURL                *url     = [NSURL URLWithString:searchString];
NSURLRequest         *request = [NSURLRequest requestWithURL:url];
NSURLSession         *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task    = [session dataTaskWithRequest:request completionHandler:^
                                 (NSData *data, NSURLResponse *response, NSError *error)
                                 {
                                     NSLog(@"ERROR: %@", error);
                                     NSLog(@"DATA: %@", data);

                                     NSError *parsingError = error;
 /*
                                     NSDictionary *root =
                                     [NSJSONSerialization JSONObjectWithData:
                                      data options:kNilOptions error: &parsingError];
*/
                                     NSDictionary *root =
                                     [NSJSONSerialization JSONObjectWithData:
                                      data options:NSJSONReadingAllowFragments error: &parsingError];

                                     NSLog(@"root: %@", root);

                                     if (!parsingError) {

                                        dispatch_async(dispatch_get_main_queue(), ^{

                                            NSDictionary *dict = [root objectForKey:@"ResultSet"];
                                            NSLog(@"dict: %@", dict);

                                        });

                                     } else {

                                         NSLog(@"Could not parse json: %@", parsingError);

                                     }

                                 }];

[task resume];
[self.view endEditing:YES];

}

雅虎似乎正在推出 JSONP(JSON 带填充)。可悲的是,解决方案看起来像 "take a substring of whatever's inside the parentheses and parse that."

How to parse JSONP in Objective-C?

答案是这是一个jsonp; json 带有填充,我需要解析掉额外的文本以使其符合 json。感谢 rikkigibson,解决方案是这样的:

if (data) {
          NSLog(@"data");
          NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
          NSLog(@"jsonString: %@", jsonString);

          NSRange range = [jsonString rangeOfString:@"("];
          range.location++;
          range.length = [jsonString length] - range.location - 1; // removes parens and trailing semicolon
          NSString *jsonString = [jsonString substringWithRange:range];
          NSLog(@"jsonString after cut: %@", jsonString);
          NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

          NSError *jsonError = nil;
          NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&jsonError];
          NSLog(@"jsonResponse: %@", jsonResponse);

       if (jsonResponse) {
       // process jsonResponse as needed
       } else {
       NSLog(@"Unable to parse JSON data: %@", jsonError);
       }
       } else {
       NSLog(@"Error loading data: %@", error);
       }
       if (!parsingError) { dispatch_async(dispatch_get_main_queue(), ^{
       // Do stuff here
       });

       } else {

       NSLog(@"Could not parse json: %@", parsingError);

       }

       }];

[task resume];
[self.view endEditing:YES];

}