简体   繁体   中英

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).

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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