简体   繁体   English

解析 JSON 显示 nil 值

[英]Parsing JSON showing nil value

I am parsing the data it gets all the data in dictionary but when i check value using NSLog it showa nil value我正在解析数据,它获取字典中的所有数据,但是当我使用 NSLog 检查值时,它显示 nil 值

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;

 }

I'm guessing that your dictionary doesn't contain a "location", and that's consistent with what I see coming back from that web site.我猜您的字典不包含“位置”,这与我从该 web 站点返回的内容一致。 It sends back an array of dictionaries which contain arrays of dictionaries.它发回包含字典 arrays 的字典数组。 You need to extract one of those inner dictionaries to find a "location".您需要提取其中一个内部词典才能找到“位置”。

[

    {
        "date":1320883200000,
        "events":[
            {
                "affectedDate":1320883200000,
                "event":{
                    "appId":620,
                    "eventId":20672,
                    "location":"Samsen Kulturhus",
                    "municipality":"Kristiansand",
                    "title":"AKKS kurs høsten 2011"
                }
            },
         ....

Try:尝试:

- (id)initWithDictionary:(NSDictionary*) dict {
   self = [super init];
   if(self) {
      self.date = [dict valueForKey:@"date"];
      self.location =  [dict valueForKey:@"location"];
      self.municipality = [dict valueForKey:@"municipality"];
      self.title =  [dict valueForKey:@"title"];
   }
   return self;
}

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

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