可编码Swift JSON解析嵌套JSON

时间:2018-08-27 05:03:02

标签: json swift4

我有如下所示的JSON数据

{
    "latitude": 34.088051,
    "longitude": -118.296512,
    "timezone": "America/Los_Angeles",
    "daily": {
        "summary": "No precipitation throughout the week, with high temperatures rising to 92°F on Friday.",
        "icon": "clear-day",
        "data": [
            {
                "time": 1535266800,
                "summary": "Mostly cloudy in the morning.",
                "icon": "partly-cloudy-day",
                "sunriseTime": 1535289854,
                "sunsetTime": 1535336915,
                "moonPhase": 0.51}

我想从中提取时间,摘要,图标。

我创建了WeatherObject类型的类,但这就是我遇到的问题。如何创建结构?这些键不是用大写字母写的,也不用错误命名的,因此我认为不用枚举即可重命名变量名。

编辑:执行-捕捉失败。 VC实现协议。传递给协议方法的数据在方法实现中打印,但在do子句中无法处理。

protocol NetworkingDelegate: AnyObject {
    func didGetResult(data: Data?) -> Void
}


class Networking: NSObject {

    var data: Data?
    weak var delegate: NetworkingDelegate?

    func makeAPIRequest(apiString: String) -> Void {
        guard let url: URL = URL(string: apiString) else{
            print("ERROR no URL")
            return
        }

        let urlRequest = URLRequest(url: url)

        let dataSession = URLSession.shared
        let dataTask = dataSession.dataTask(with: urlRequest) { (data, response, error) in

            guard error == nil else{
                print("ERROR found in networking call")
                print(error!)
                return
            }

            if data != nil{

                print("Data exists in networking")
                self.delegate?.didGetResult(data: data!)




            }else{
                print("ERROR: did not receive data")
            }
        }

        dataTask.resume()
    }


}

在ViewController中

  func didGetResult(data: Data?) {



            do {

                if let dataObject = data{

                    let theString:NSString = NSString(data: dataObject, encoding: String.Encoding.ascii.rawValue)!
                    print(theString)
                }
                let newJSONDecoder = JSONDecoder()
                let weatherObject = try newJSONDecoder.decode(WeatherObj.self, from:data!)
                let dailyObject = weatherObject.daily
                let dataArray = dailyObject.data
                //LOOP THROUGH dataArray and get the required info
                for val in dataArray {
                    print("=======")
                    print(val.time)
                    print(val.summary)
                    print(val.icon)
                    print("=======")
                }
            } catch {
                print("error while parsing:\(error.localizedDescription)")
            }


        }

1 个答案:

答案 0 :(得分:2)

您可以像这样创建结构

struct WeatherObject: Codable {
  let latitude: Double
  let longitude: Double
  let timezone: String
  let daily: Daily
}

struct Daily: Codable {
    let summary: String 
    let icon: String
    let data: [Datum]
}

struct Datum: Codable {
    let time: Int
    let summary: String
    let icon: String
    let sunriseTime: Int
    let sunsetTime: Int
    let moonPhase: Double
}

然后您可以解析它并获取所需的信息

do {
    let newJSONDecoder = JSONDecoder()
    let weatherObject = try newJSONDecoder.decode(WeatherObject.self, from: jsonData)
    let dailyObject = weatherObject.daily
    let dataArray = dailyObject.data
    //LOOP THROUGH dataArray and get the required info
    for val in dataArray {
        print("=======")
        print(val.time)
        print(val.summary)
        print(val.icon)
        print("=======")
    }
} catch {
    print("error while parsing:\(error.localizedDescription)")
}

希望有帮助

相关问题