带模型的 SwiftyJson 嵌套数组

SwiftyJson nested array with model

如何使用 SwiftyJSON 和第二组嵌套对象数组创建数据模型?我能够很好地解析和存储顶级对象,但不能解析和存储内部对象。特别是noteimages,我似乎无法弄清楚。下面是 api 结果,下面是我尝试这样做的方法,尽管不太正确。

[
{
    "id": 1,
    "title": "some title",
    "details": "here are some details",
    "userId": 1,
    "hidden": false,
    "createdAt": "2018-02-14T07:02:33.000Z",
    "updatedAt": "2018-02-14T07:02:33.000Z",
    "contactId": 1,
    "noteimages": [
        {
            "id": 2,
            "imageUrl": "someimage222.jpg",
            "userId": 1,
            "hidden": false,
            "createdAt": "2018-02-14T07:02:58.000Z",
            "updatedAt": "2018-02-15T04:41:05.000Z",
            "noteId": 1
        }
    ]
}
]

Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: header).responseJSON { (response) in

        if response.result.error == nil {
            guard let data = response.data else { return }
            do {
                if let json = try JSON(data: data).array {
                    print(json)
                    for item in json {
                        let title = item["title"].stringValue
                        let details = item["details"].stringValue

                        var noteImages: [Dictionary<String, AnyObject>]
                        for image in item["noteimages"].arrayValue {
                            noteImages.append(image["imageUrl"])
                        }

                        let note = Note(title: title, details: details, noteImage: noteImages)
                        self.notes.append(note)
                    }
                    //print(response)
                    completion(true)
                }
            } catch {
                debugPrint(error)
            }

        } else {
            completion(false)
            debugPrint(response.result.error as Any)
        }

    }

你的问题是你正在获取键 imageUrl 中的值字符串并且你正在添加为字典所以如果你需要一个字典数组你需要直接在 item["noteimages"].arrayValue 中添加这些值或者如果您需要 imageUrl 的数组,则需要将 noteImages var 的类型更改为 String type

var noteImages: [Dictionary<String, AnyObject>]// this should be [String:AnyObject]] swifty way
for image in item["noteimages"].arrayValue {
    noteImages.append(image["imageUrl"]) //this is an String not an Dictionary
}

要解决此问题,您需要三个选项之一

方案一:使用字典数组

var noteImages: [[String:AnyObject]] = []
for image in item["noteimages"].arrayValue {
   if let imageDict = image as? [String:AnyObject]{
       noteImages.append(imageDict) //adding in a dictionary array
    }
}

选项 2:使用字符串数组

var noteImages: [String] = []
for image in item["noteimages"].arrayValue {
   if let imageDict = image as? [String:AnyObject]{
       noteImages.append(imageDict["imageUrl"])
    }
}

选项 3:将字典转换为模型对象

var noteImages: [YourModelName] = []
for image in item["noteimages"].arrayValue {
   if let imageDict = image as? [String:AnyObject]{
       noteImages.append(YourModelName(dictionary:imageDict)) //adding in a model object created from a dictionary
    }
}

这就是我最后做的事情:

var notes = [Note]()
var noteImages = [NoteImage]()

.....

    Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: header).responseJSON { (response) in

        if response.result.error == nil {
            guard let data = response.data else { return }
            do {
                if let json = try JSON(data: data).array {
                    print(json)
                    for item in json {
                        let title = item["title"].stringValue
                        let details = item["details"].stringValue

                        //loop through nested array
                        for innerItem in item["noteimages"].arrayValue {
                            let noteImage = NoteImage(imageUrl: innerItem["imageUrl"].stringValue)
                            self.noteImages.append(noteImage)
                        }

                        print("note images: \(self.noteImages)")

                        let note = Note(title: title, details: details, noteImage: self.noteImages)
                        self.notes.append(note)
                    }
                    //print(response)
                    completion(true)
                }
            } catch {
                debugPrint(error)
            }

        } else {
            completion(false)
            debugPrint(response.result.error as Any)
        }

    }