【问题标题】:SwiftyJson nested array with modelSwiftyJson 嵌套数组与模型
【发布时间】:2018-07-28 16:16:59
【问题描述】:

如何使用 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)
        }

    }

【问题讨论】:

    标签: ios json swift swifty-json


    【解决方案1】:

    您的问题是您在键 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
        }
    }
    

    【讨论】:

    • 谢谢,你是对的。我刚刚打印了那个数据,它是一个字符串。尝试使用错误的类型构建模型。
    【解决方案2】:

    这就是我最终做的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-06
      • 2017-09-26
      • 1970-01-01
      • 2013-03-15
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      相关资源
      最近更新 更多