简体   繁体   English

循环遍历 JSON 数据并将其存储在数组中

[英]Loop through JSON data and store it in array

So I have JSON data that's in an array (0 is first day of month up until last day of month).所以我有一个数组中的 JSON 数据(0 是一个月的第一天直到一个月的最后一天)。

How do I do a loop to go through the whole array and store the 3 times of the day each in their own array (I wish to use these times for notifications later)如何循环遍历整个数组并将一天中的 3 次存储在各自的数组中(我希望稍后将这些时间用于通知)

The dayForArray variable is just the current day - 1 so that it matches the number in the JSON array. dayForArray 变量只是当前日期 - 1,以便它与 JSON 数组中的数字相匹配。

func parseJSON(_ timesData: Data) -> TimesModel? {
    let decoder = JSONDecoder()
    do {
        let decodedData = try decoder.decode(TimesData.self, from: timesData)
        let time1 = decodedData.data[dayForArray].timings.Time1
        let time2 = decodedData.data[dayForArray].timings.Time2
        let time3 = decodedData.data[dayForArray].timings.Time3

        let time = TimeModel(time1: time1, time2: time2, time3: time3)

        return times

    } catch {
        delegate?.didFailWithError(error: error)
        return nil
    }
}

What you need to do is to use map to create an array of TimeModel objects from your json array您需要做的是使用map从您的 json 数组创建一个TimeModel对象数组

let times = decodedData.data.map { 
    TimeModel(time1: $0.timings.Time1, 
              time2: $0.timings.Time2, 
              time3: $0.timings.Time3) 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM