【问题标题】:Get contents of JSON file based on Todays Date根据今天日期获取 JSON 文件的内容
【发布时间】:2015-04-18 23:01:48
【问题描述】:

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

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

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

例如:拉入当天的图文,显示在屏幕上

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

**Days.json**sn-p:

{
    "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"];

【问题讨论】:

    标签: ios objective-c json xcode uiviewcontroller


    【解决方案1】:

    JSON 被解析为带有键“days”和对象数组作为值的字典。因此,您可以遍历对象以找到您想要的对象。

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

    【讨论】:

    • 感谢您的回复!以这种方式迭代是有道理的。你会用todayInJson 做什么?我想我知道它会类似于NSString *timToday = [todayInJson valueForKey:@"tim"];,但只是想与您再次确认。你也会这样做吗?
    • 是的。或 todayInJson["day"]。 Json 可以包含对象(与字典相同),如果它们有 { 或数组,如果它们有 [
    猜你喜欢
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多