根据今日日期获取JSON文件的内容

时间:2015-04-18 23:01:49

标签: ios objective-c json xcode uiviewcontroller

我有一个应用程序,每天会根据该日期显示不同的内容

即。 1月1日将有picture1,1月2日将有picture2等。

我在本地获取了Days.json文件中的所有数据,我知道如何拉当前日期,但我不能弄清楚如何获取特定日期的数据

例如:拉入当天的图片和文字,并将其显示在屏幕上

有什么想法吗?将根据需要发布任何额外的代码!

**Days.json**摘录:

{
    "days": [
            {
            "day": "Jan 1",
            "topic": "1 Endurance",
            "image": "picture1"
            },
            {
            "day": "Jan 2",
            "topic": "2 Endurance"
            "image": "picture2"
            },
            {
             "day": "Apr 18",
             "topic": "3 Endurance",
            "image": "picture3"
            }
            ]
}

**ViewController.m**

//Get todays date to match date format in Days.json
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
NSString *dateToday = [formatter stringFromDate:[NSDate date]];
NSLog(@"Date Today: %@", dateToday);
// Remove the year from current date string
NSString *dateTodayShort = [dateToday substringToIndex:[dateToday length]-6];
NSLog(@"Date Today Short: %@", dateTodayShort);

// Get the json file
NSString *JSONFilePath = [[NSBundle mainBundle] pathForResource:@"Days" ofType:@"json"];
NSData *JSONData = [NSData dataWithContentsOfFile:JSONFilePath];
NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil];
days = JSONDictionary[@"days"];
NSString *day = [days valueForKey:@"day"];

1 个答案:

答案 0 :(得分:1)

JSON被解析为带有键"天"的字典。和一个对象数组作为值。因此,您可以迭代对象以找到所需的对象。

NSObjet *todayInJson;
for (NSObject *object in days) {
  NSString *date_object = [object valueForKey:@"day"];
  if [date_object isEqualToString:dateTodayShort] {
     todayInJson = object;
     //object found..
  }
}