有人可以帮我解析下面的jsonData到nsDictionary对象
[{“id”:“22144”,“t”:“AAPL”,“e”:“纳斯达克”,“l”:“111.57” ,“l_fix”:“111.57”,“l_cur”:“111.57”,“s”:“2”,“ltt”:“美国东部时间下午4:00” ,“lt”:“美国东部时间11月28日下午4:00”,“lt_dts”:“2016-11-28T16:00:01Z”,“c”: “-0.22”,“c_fix”:“ - 0.22”,“cp”:“ - 0.20”,“cp_fix”:“ - 0.20”,“ccol” :“chr”,“pcls_fix”:“111.79”,“el”:“111.56”,“el_fix”:“111.56” ,“el_cur”:“111.56”,“elt”:“美国东部时间11月28日晚上8点”,“ec”:“ - 01” ,“ec_fix”:“ - 01”,“ecp”:“ - 01”,“ecp_fix”:“ - 01”,“eccol”: “chr”,“div”:“0.57”,“yld”:“2.04”}]
#define QUERY_PREFIX @"https://www.google.com/finance/info?q=NSE:AAPL"
#define QUERY_SUFFIX @"NSE:AAPL"
@implementation YQL
- (NSDictionary *) query: (NSString *)statement {
NSString *query = [NSString stringWithFormat:@"%@%@%@", QUERY_PREFIX, [statement stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], QUERY_SUFFIX];
NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
NSString *dataString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSUInteger firstCurlyBracePos = [dataString rangeOfString:@"[" options:0].location;
NSUInteger lastCurlyBracePos = [dataString rangeOfString:@"]" options: NSBackwardsSearch].location;
NSString *jsonString = nil;
if(firstCurlyBracePos != NSNotFound && lastCurlyBracePos != NSNotFound) {
jsonString = [dataString substringWithRange:NSMakeRange(firstCurlyBracePos, (lastCurlyBracePos-firstCurlyBracePos)+1)];
}
NSData *someData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@ Nirmal",jsonString);
NSError *error = nil;
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:someData options:0 error:&error];
NSLog(@"%@ Anand",results);
NSString* latestLoans = [results objectForKey:@"el_cur"];
NSLog(@"loans: %@", latestLoans);
if (error) NSLog(@"[%@ %@] JSON error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);
return results;
}
@end
由于未捕获的异常而终止应用 'NSInvalidArgumentException',原因:' - [__ NSSingleObjectArrayI objectForKey:]:无法识别的选择器发送到实例0x61800000d010'
答案 0 :(得分:1)
您尝试解析的JSON是一个数组,而不是一个对象,由括号方括号表示。所以NSJSONSerialization将在这里返回一个NSArray,而不是NSDictionary。由于此数组中似乎只有一个对象,因此您可以像这样访问它:
NSArray *results = [NSJSONSerialization JSONObjectWithData:someData options:0 error:&error];
NSDictionary *object = results.firstObject;
NSString *latestLoans = object["el_cur"];