简体   繁体   English

解析 JSON 显示 nil 值

[英]Parsing JSON showing nil value

SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=350&counties-selected=Vest-Agder,Aust-Agder"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *object = [parser objectWithString:json_string error:nil];
//appDelegate.books = [[NSMutableArray alloc] initWithCapacity:0];
appDelegate.books1 = [[NSMutableArray alloc] init];

NSArray *results = [parser objectWithString:json_string error:nil];
for (int i=0; i<[results count]; i++) {
    Book1  *aBook = [[Book1 alloc] initWithDictionary:[results objectAtIndex:i]];
    [appDelegate.books1 addObject:aBook];
    Book1 *mybook=[appDelegate.books1 objectAtIndex:i];
    NSString*test=mybook.location;
    NSLog(test);
}

Dicionary parsing字典解析

- (id)initWithDictionary:(NSDictionary*) dict {

    self.date = [dict valueForKey:@"date"];
    self.location =  [dict valueForKey:@"location"];
    self.municipality = [dict valueForKey:@"municipality"];
    self.title =  [dict valueForKey:@"title"];

    return self;
}
NSDictionary *object = [parser objectWithString:json_string error:nil]; 
.. 
NSArray *results = [parser objectWithString:json_string error:nil];

For once, you might need to decide whether the data you want to parse should be an NSArray or an NSDictionary (see above: you assign the same string once to any of them).这一次,您可能需要决定要解析的数据应该是 NSArray 还是 NSDictionary(见上文:您将相同的字符串分配给它们中的任何一个)。

Generally speaking: your data is wrong (most likely incorrectly formatted) which is the most likely reason for SBJson to return nil, however, passing an NSError to the error parameter might give you the real reason (that's what's error handling really is for)一般来说:您的数据错误(很可能格式不正确),这是 SBJson 返回 nil 的最可能原因,但是,将 NSError 传递给错误参数可能会给您提供真正的原因(这就是错误处理的真正用途

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM