SwiftyJson嵌套数组与模型

时间:2018-02-18 06:25:58

标签: ios json swift swifty-json

如何使用SwiftyJSON和第二组嵌套对象数组创建数据模型?我能够很好地解析和存储顶级对象,但不能解析内层对象。特别是注意事项,我似乎无法弄清楚。下面是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)
        }

    }

2 个答案:

答案 0 :(得分:3)

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

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
}

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

选项1:使用字典数组

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
    }
}

答案 1 :(得分:0)

这就是我最终做的事情:

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)
        }

    }