检查嵌套json响应的值

时间:2013-08-23 14:23:40

标签: ios json nsarray

我希望从我的谷歌地方json响应得到关闭时间取决于当前的日期。这行代码为我提供了当前当天的0-6值。

NSString *dayOfWeek = [myFormatter stringFromDate:today];

我有一个NSArray来存储谷歌地方响应的结果。

NSArray* periods= [[place objectForKey:@"opening_hours"]objectForKey:@"periods"];

句点数组中的json响应如下所示。

Period RESULT (
        {
        close =         {
            day = 0;
            time = 2300;
        };
        open =         {
            day = 0;
            time = 1100;
        };
    },
        {
        close =         {
            day = 1;
            time = 2300;
        };
        open =         {
            day = 1;
            time = 1100;
        };
    },
        {
        close =         {
            day = 2;
            time = 2300;
        };
        open =         {
            day = 2;
            time = 1100;
        };
    },
        {
        close =         {
            day = 3;
            time = 2300;
        };
        open =         {
            day = 3;
            time = 1100;
        };
    },
        {
        close =         {
            day = 4;
            time = 2300;
        };
        open =         {
            day = 4;
            time = 1100;
        };
    },
        {
        close =         {
            day = 5;
            time = 2300;
        };
        open =         {
            day = 5;
            time = 1100;
        };
    },
        {
        close =         {
            day = 6;
            time = 2300;
        };
        open =         {
            day = 6;
            time = 1100;
        };
    }
)

如何使用dayOfWeek值检查句点数组的正确close.time?

2 个答案:

答案 0 :(得分:1)

for( NSDictionary *d in periods ){
  NSInteger day = [[[d objectForKey:@"close"] objectForKey:@"day"] integerValue];

  if( day == [dayOfWeek integerValue] ){
    return [[[d objectForKey:@"close"] objectForKey:@"time"] integerValue];
  }
}

答案 1 :(得分:-1)

您可以采用的一种方法是利用NSPredicateKey-Value Coding

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"close.day = %@", dayOfWeek];
NSArray *output = [periods filteredArrayUsingPredicate:predicate];
NSNumber *closingTime = [output.lastObject valueForKeyPath:@"close.time"];