如何将值附加到模型类

时间:2019-07-08 10:48:15

标签: ios swift alamofire

我有一个模型类,我需要从JSON附加值,我正在使用Alamofire

我尝试了以下方法,但是这些值未正确添加。

这是模型类

class ImageMJ {
var assignment__assignment_name:String?
var assignment__file_up:String?

init(assignment__assignment_name: String?, assignment__file_up: String?) {
    self.assignment__assignment_name = assignment__assignment_name
    self.assignment__file_up = assignment__file_up
  }
}

还有我曾经用过的乐趣

var imageDetailsArrayMJ = [ImageMJ]()

Alamofire.request(urls, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
        if((response.result.value) != nil) {
             let jsonVar = JSON(response.result.value!)
//                print(jsonVar)



            if let items = jsonVar["assisgnments"].array  {
                for item in items {

                    if let ids = item["assignment__assignment_name"].string {
                        print("IDS ==   \(ids)")
                        self.imageDetailsArrayMJ.append(ImageMJ(assignment__assignment_name: ids as! String, assignment__file_up: nil))

                    }

                    if let ifd = item["assignment__file_up"].string {
                        self.imageDetailsArrayMJ.append(ImageMJ(assignment__assignment_name: nil, assignment__file_up: ifd as! String))
                    }
                }


            }

我的JSON是

{
"assisgnments": [
    {
        "assignment__file_up": "media/"
        "assignment__assignment_name": "MAX PAYNE",
    },
    {
        "assignment__file_up": "media/assignments/Calendar-master.zip",
        "assignment__assignment_name": "Doctor",
    },
    {
        "assignment__assignment_desc": "EA SPORTS FIFA 20",
        "assignment__file_up": "media/assignments/Screen_Shot_2019-07-08_at_10.38.49_AM.png",
    }
]}

我需要这样     assignment__assignment_name =“ MAX PAYNE”,     assignment__file_up =“ media / assignments / Calendar-master.zip”

1 个答案:

答案 0 :(得分:1)

不必为每个字典值创建一个新项目,而必须在每次迭代中创建一个一个项目。

因为这些属性都是可选的,所以您不需要检查(也不需要类型转换)

 if let items = jsonVar["assisgnments"].array  {
    for item in items {

        let ids = item["assignment__assignment_name"].string 
        let ifd = item["assignment__file_up"].string
        self.imageDetailsArrayMJ.append(ImageMJ(assignment__assignment_name: ids, assignment__file_up: ifd))
    }
 }

我们鼓励您放弃SwiftyJSON而使用Codable,并摆脱那些难看的 objective-c-ish 下划线。