从JSON获取特定值

时间:2017-06-30 10:05:23

标签: ios json swift

let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
 print(json)

我的打印声明给出了以下结果:

`Result =  [ 
        {
    Friday = 0;
    Monday = 0;
    Saturday = 0;
    Sunday = 0;
    Thursday = 0;
    Tuesday = 0;
    Wednesday = 1;
},
        {
    Friday = 1;
    Monday = 0;
    Saturday = 0;
    Sunday = 0;
    Thursday = 0;
    Tuesday = 0;
    Wednesday = 0;
}]

我希望得到价值为1的日子(在{周围和星期五的JSON以上) 如何遍历此JSON? 提前谢谢。

2 个答案:

答案 0 :(得分:-1)

首先检查您的数据是否有效JSON。如果它然后使用下面的循环来获得日子

     var daysList = [String]()

     for dict in Result {
           for values in dict {
              if let days = values.value as? Int,let values.value! == 1 {
                    daysList.append(days)
               }else{
                  //Sometimes 0 and 1 values doesn't casting as? Int.So probably you can try out with Bool
                  if let days = values.value as? Bool,let values.value! == 1 {
                     daysList.append(days)
                  }
               }
            }
        }

print(daysList) // Wednesday,Friday

答案 1 :(得分:-2)

这是目标c中的一个例子:

///Parse Json
NSArray *arrResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL];

///Iterate data and form a dictionary with days having 1
NSMutableDictionary *dictDays = [NSMutableDictionary dictionary];

for (NSDictionary *dictWeek in arrResult) {

    for (NSString *strDay in [dictWeek allKeys]) {

        if ([[dictWeek objectForKey:strDay]intValue] == 1) {

            [dictDays setObject:@1 forKey:strDay];

        }

    }
}

///Print the days having 1
for (NSString *strDay in [dictDays allKeys]) {

    NSLog(@"Day Name: %@",strDay);
}