如何从NSMutableDictionary中获取值

时间:2017-10-14 04:55:26

标签: ios swift nsmutabledictionary

我试图从NSMutableDictionary中获取价值我无法接受它,因为它具有多维度

{
    "seleted_days" =     (
        TUE,
        WED
    );
    timings =     (
                (
        ),
                (
        ),
                (
                        {
                "close_time" = "05:00 AM";
                "open_time" = "02:00 AM";
                timelist = "02:00 AM , 03:00 AM , 04:00 AM , 05:00 AM";
                timestat = "1,0,0,1";
            }
        ),
                (
                        {
                "close_time" = "05:00 AM";
                "open_time" = "02:00 AM";
                timelist = "02:00 AM , 03:00 AM , 04:00 AM , 05:00 AM";
                timestat = "1,0,0,1";
            }
        ),
                (
        ),
                (
        ),
                (
        )
    );
}

需要从此NSMutableDictionary

获取开放时间和结束时间

我尝试过的代码

let array:NSArray =  myretrievedic.value(forKey: "timings") as! NSArray
             for i in 0...array.count
             {

            let subArray:NSArray = array.object(at: i) as! NSArray
            if let dict:NSDictionary = subArray.object(at: 0) as! NSDictionary
            {

            let close_time:String = dict.value(forKey: "close_time") as! String
            let open_time:String = dict.value(forKey: "open_time") as! String


            print(open_time)
            print(close_time)
            }

当null出现时它会崩溃,即使我把let语句放进去。我也不明白为什么如果让语句不起作用

2 个答案:

答案 0 :(得分:1)

key timings的值是一个数组数组。

这是仅使用Swift本机集合类型的原生Swift解决方案。它包括反序列化JSON的行。 data是JSON字符串Data utf8 encoded

do {       
    if let root = try JSONSerialization.jsonObject(with: data) as? [String:Any],
        let timings = root["timings"] as? [[Any]] {
        for timing in timings where !timing.isEmpty {
            if let times = timing.first as? [String:String] {
                let openTime = times["open_time"]!
                let closeTime = times["close_time"]!
                print(openTime, closeTime)
            }
        }
    }
} catch {
    print(error)
}

答案 1 :(得分:-1)

let dictionary:NSMutableDictionary = NSMutableDictionary()

    let array:NSArray =  dictionary .value(forKey: "timings") as! NSArray


    for i in 0...array.count
    {
        let subArray:NSArray = array.object(at: 2) as! NSArray

        if subArray.count > 0 {

            let dict:NSMutableDictionary = subArray.object(at: 0) as! NSMutableDictionary

            let close_time:String = dict.value(forKey: "close_time") as! String
            let open_time:String = dict.value(forKey: "open_time") as! String
        }
    }