解析JSON显示nil值

时间:2011-07-23 06:52:48

标签: iphone objective-c json sbjson

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;
}

1 个答案:

答案 0 :(得分:2)

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

一次,您可能需要确定要解析的数据是NSArray还是NSDictionary(参见上文:您为其中任何一个分配相同的字符串)。

一般来说:你的数据错误(很可能是格式不正确),这是SBJson返回nil的最可能原因,但是,将NSError传递给error参数可能会给你真正的原因(这就是错误处理的真正原因< em>是 for)