我想从JSON文件中获取特定数据

时间:2019-03-30 01:35:23

标签: ios json swift xcode

我正在尝试从此json文件中获取“时间”数据:

{"code":200,"status":"OK","results":{"datetime":[{"times":
{"Imsak":"04:18","Sunrise":"05:48","Fajr":"04:28","Dhuhr":"12:00","Asr":"15:30","Sunset":"18:13","Maghrib":"18:26","Isha":"19:32","Midnight":"23:20"},"date":{"timestamp":1553817600,"gregorian":"2019-03-29","hijri":"1440-07-22"}}],
"location":{"latitude":30.04442024230957,"longitude":31.2357120513916,"elevation":30.0,"city":"Cairo","country":"Egypt","country_code":"EG","timezone":"Africa/Cairo","local_offset":2.0},
"settings":{"timeformat":"HH:mm","school":"Ithna Ashari","juristic":"Shafii","highlat":"None","fajr_angle":18.0,"isha_angle":18.0}}}

但是我不知道如何仅获取此行的数值: {"datetime":[{"times": {"Imsak":"04:18","Sunrise":"05:48","Fajr":"04:28","Dhuhr":"12:00","Asr":"15:30","Sunset":"18:13","Maghrib":"18:26","Isha":"19:32","Midnight":"23:20"}

我写了这个函数

let urlString = "https://api.pray.zone/v2/times/today.json?city=cairo"

    func getDataFromURL() {
        let url = URL(string: urlString)
        URLSession.shared.dataTask(with: url!) { (data, response, error) in
            if error != nil {
                print(error!.localizedDescription)
            } else {
                do {
                    let parsedData = try JSONSerialization.jsonObject(with: data!) as! [String: Any]
                    print(parsedData)
                } catch let error as NSError {
                    print(error.localizedDescription)
                }
            }
        }.resume()
    }
}

我想用正确的行替换print(parsedData),使我能够从文件中获得祈祷时间。

2 个答案:

答案 0 :(得分:2)

根据您的Json,一个原始的解决方案:

//......

//lines from print(parsedData)
print(parsedData)

if let results = parsedData["results"] as? [String:Any] {
    if let datetimes = results["datetime"] as? [Any] {
        for datetime in datetimes {
            if let datetimeDict = datetime as? [String:Any] {
                if  let times = datetimeDict["times"] as? [String:String] {
                    let timeNumbers = times.values.sorted()
                    print(timeNumbers)
                }
            }
        }
    }
}

//......

输出:

["04:17", "04:27", "05:47", "12:00", "15:30", "18:13", "18:27", "19:33", "23:20"]

答案 1 :(得分:1)

以下使用JSONDecoder读取您的数据。

// Parsing data //
do {
    let result = try JSONDecoder().decode(MyData.self, from: data!)
    let results = result.results
    let dateTime = results.datetime
    let times = dateTime[0].times
    print(times) // TimeData(Imsak: "04:18", Sunrise: "05:48", Fajr: "04:28", Dhuhr: "12:00", Asr: "15:30", Sunset: "18:13", Maghrib: "18:26", Isha: "19:32", Midnight: "23:20")
} catch let error as NSError {
    print("\(error)")
}

// MyData.swift //
import UIKit

struct MyData: Decodable {
    let code: Int
    let status: String
    let results: ResultsData
}

struct ResultsData: Decodable {
    let datetime: [DateTimeData]
    let location: LocationData
    let settings: SettingsData
}

struct DateTimeData: Decodable {
    let times: TimeData
    let date: DateData
}

struct TimeData: Decodable {
    let Imsak: String
    let Sunrise: String
    let Fajr: String
    let Dhuhr: String
    let Asr: String
    let Sunset: String
    let Maghrib: String
    let Isha: String
    let Midnight: String
}

struct DateData: Decodable {
    let timestamp: Double
    let gregorian: String
    let hijri: String
}

struct LocationData: Decodable {
    let latitude: Double
    let longitude: Double
    let elevation: Double
    let city: String
    let country: String
    let country_code: String
    let timezone: String
    let local_offset: Double
}

struct SettingsData: Decodable {
    let timeformat: String
    let school: String
    let juristic: String
    let highlat: String
    let fajr_angle: Double
    let isha_angle: Double
}