How to create objects from SwiftyJSON

后端 未结 4 1142
面向向阳花
面向向阳花 2021-02-19 06:23

I have a code, that parses JSON\'s list of questions and I can get every property. How can I iterate through the whole file and for each question create an object ?

<         


        
4条回答
  •  日久生厌
    2021-02-19 07:04

    Step 1. We will create one protocol with one constructor method in it and Model class

    protocol JSONable {
        init?(parameter: JSON)
    }
    
    class Style: JSONable {
        let ID              :String!
        let name            :String!
    
        required init(parameter: JSON) {
            ID            = parameter["id"].stringValue
            name          = parameter["name"].stringValue
        }
    
        /*  JSON response format
        {
          "status": true,
          "message": "",
          "data": [
            {
              "id": 1,
              "name": "Style 1"
            },
            {
              "id": 2,
              "name": "Style 2"
            },
            {
              "id": 3,
              "name": "Style 3"
            }
          ]
        }
        */
    }
    

    Step 2. We will create extension of JSON which will convert JSON to model class type object

    extension JSON {
        func to(type: T?) -> Any? {
            if let baseObj = type as? JSONable.Type {
                if self.type == .array {
                    var arrObject: [Any] = []
                    for obj in self.arrayValue {
                        let object = baseObj.init(parameter: obj)
                        arrObject.append(object!)
                    }
                    return arrObject
                } else {
                    let object = baseObj.init(parameter: self)
                    return object!
                }
            }
            return nil
        }
    }
    

    Step 3. Use code with Alamofire or other code.

    Alamofire.request(.GET, url).validate().responseJSON { response in
            switch response.result {
                case .success(let value):
                    let json = JSON(value)
    
                    var styles: [Style] = []
                    if let styleArr = json["data"].to(type: Style.self) {
                        styles = styleArr as! [Style]
                    }
                    print("styles: \(styles)")
                case .failure(let error):
                    print(error)
            }
     }
    

    I hope this will be useful.

    Please refer to this link for more information on this.
    https://github.com/SwiftyJSON/SwiftyJSON/issues/714

提交回复
热议问题