Objective C NSDictionary JSON在一行中

时间:2017-06-19 14:43:27

标签: objective-c

我正在开发一个目标C应用程序,我正在使用JSON数据,我需要在Dictionary fillDefaultColors中插入这些数据(日期)。我的fillDefaultColors应该是这样的格式:

self.fillDefaultColors = @{    @"2017/06/18":greenColor,
                               @"2017/06/19":orangeColor,
                               @"2017/06/20":greenColor,
                               ...
                               };

但是当我在控制台日志中打印时,它们每个都在单独的行中,在应用程序中我只能看到JSON中最后一项的颜色

2017-06-19 15:30:12.310 CalendarTest[1905:364525] {
    "2017/06/20" = "greenColor";
}
2017-06-19 15:30:12.311 CalendarTest[1905:364525] {
    "2017/06/18" = "orangeColor";
}

所以在应用程序中,我在控制台2017/06/18中看到了最后日期的背景

这是我的代码

NSError *error = nil;
    NSURL *url = [NSURL URLWithString: @"http://..."];
    NSData *data = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];

   if(!error)
    {
        NSDictionary* json = [NSJSONSerialization
                              JSONObjectWithData:data
                              options:NSJSONReadingMutableContainers
                              error:&error];

       NSMutableArray *array= [json objectForKey:@"horses"];

       for(int i=0; i< array.count; i++)
        {
            NSDictionary *horsedata = [array objectAtIndex:i];
            NSString *date = [horsedata objectForKey:@"date"];
            NSNumber *averagetemp = [horsedata objectForKey:@"averagetemperature"];
            if([averagetemp isEqual:@(28)]) {tempColor = greenColor;} else {
                tempColor = orangeColor;
            }
            self.fillDefaultColors = @{date: tempColor};
            NSLog(@"%@", _fillDefaultColors);

       }

   }

JSON: {"horses":[{"id":1,"name":"Horse","date":"2017/06/17","averagetemperature":28},{"id":1,"name":"Horse","date":"2017/06/18","averagetemperature":25}]}

Thanks

2 个答案:

答案 0 :(得分:1)

因为你在每次迭代中分配一个新的字典:

self.fillDefaultColors = @{date: tempColor};

你需要追加:

   NSMutableArray *array= [json objectForKey:@"horses"];
   self.fillDefaultColors = [[NSMutableDictionary alloc]init];
   for(int i=0; i< array.count; i++)
    {
        NSDictionary *horsedata = [array objectAtIndex:i];
        NSString *date = [horsedata objectForKey:@"date"];
        NSNumber *averagetemp = [horsedata objectForKey:@"averagetemperature"];
        if([averagetemp isEqual:@(28)]) {tempColor = greenColor;} else {
            tempColor = orangeColor;
        }

        [self.fillDefaultColors setObject:tempColor forKey:date];
        NSLog(@"%@", _fillDefaultColors);

   }

答案 1 :(得分:1)

这与Hussein的答案相同,但使用现代Objective-C语法 - 至少在5年前推出。

NSArray *horses = json[@"horses"];
self.fillDefaultColors = [[NSMutableDictionary alloc] init];
for (NSDictionary *horsedata in horses)
{
    NSString *date = horsedata[@"date"];
    NSNumber *averagetemp = horsedata[@"averagetemperature"];
    self.fillDefaultColors[date] = (averagetemp.integerValue == 28) ? greenColor : orangeColor;

    NSLog(@"%@", _fillDefaultColors);
}