Swift 4解析对象数组 [英] Swift 4 Parsing an Object Array

查看:304
本文介绍了Swift 4解析对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将解析代码传输到Swift4/Xcode9时遇到问题.我正在通过模型正确解析它,并且我知道问题是因为我当前正在通过根JSON对象进行解析,但是我的REST API是结构化的JSON根->数据数组->其他对象.我知道这可能很简单,但是我已经奋斗了很久了.我已经附上了REST API布局的图像,只需要知道如何进入对象以检索值即可.

I'm having problems transferring my parsing code over to Swift4/Xcode9. I'm parsing it through my model correctly and I know the problem is because I'm currently parsing through the root JSON object, however my REST API is structured JSON root -> data array -> further objects. I know it's probably simple but I've been struggling for ages. I have attached an image of the layout of my REST API, and just need to know how to step into objects to retrieve values.

    let jsonUrlString = "HIDDEN"
        guard let url = URL(string: jsonUrlString) else
            {return}

        URLSession.shared.dataTask(with: url) { (data, response, err) in

            guard let data = data else {return}

            do {

                 let show =  try
                    JSONDecoder().decode(TvHeaderModel.self, from: data)
                print(show.title)

            } catch let jsonErr {
                print("Error serializing JSON", jsonErr)
            }

        }.resume()

    struct TvHeaderModel: Decodable    {
    var id: Int?
    var title: String?
    var year: Int?
    var songCount: Int?
    var poster: String?

    init(json: [String: Any])   {
        id = json["_id"] as? Int ?? -1
        title = json["title"] as? String ?? ""
        year = json["year"] as? Int ?? -1
        songCount = json["song_count"] as? Int ?? -1
        poster = json["poster_urL"] as? String ?? ""

    }
}

推荐答案

使用JSONDecoder并将所有属性声明为可选属性并始终分配非可选值时,基本上不需要init(json初始化程序

Basically you don't need the init(json initializer when using JSONDecoder and declaring all properties as optional and assigning always a non-optional value is nonsensical anyway.

要解码季节,请添加结构

To decode also the seasons add a struct

struct Season : Decodable {
        private enum CodingKeys : String, CodingKey {
            case id = "_id", season
            case show = "tv_show", createdDate = "created_at"
            case numberOfEpisodes = "episodes_count", numberOfSongs = "songs_count"
        }

        let id, season, show, numberOfEpisodes, numberOfSongs : Int
        let createdDate : Date
}

TvHeaderModel中添加属性

let seasons : [Season]

并设置解码器的dateDecodingStrategy以解码ISO8601日期.

And set the dateDecodingStrategy of the decoder to decode ISO8601 dates.

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
decoder.decode(TvHeaderModel.self, from: data)

这篇关于Swift 4解析对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆