代码之家  ›  专栏  ›  技术社区  ›  Keith

带模型的SwiftyJson嵌套数组

  •  2
  • Keith  · 技术社区  · 7 年前

    如何使用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 回复  |  直到 7 年前
        1
  •  3
  •   Reinier Melian    7 年前

    您的问题是在键中获取值字符串 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
  •  0
  •   Keith    7 年前

    这就是我最后做的:

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