Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON to Model conversion #714

Closed
amit-bhavsar opened this issue Nov 9, 2016 · 5 comments
Closed

JSON to Model conversion #714

amit-bhavsar opened this issue Nov 9, 2016 · 5 comments
Labels

Comments

@amit-bhavsar
Copy link

Hello,
I have one solution which may be useful to many users of SwiftyJSON and who have one common question about JSON to Model conversion in proper way.
I try to make this solution, it will be useful to those users.

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

By follow these steps users can easily convert JSON object to their relative Model classes.

@VikasPrajapati27
Copy link

VikasPrajapati27 commented Nov 9, 2016

ya, I think this is very useful for me as json to model.

@ldiqual
Copy link
Contributor

ldiqual commented Nov 22, 2016

@AmitBhavsarIphone I would argue that it's not the role of SwiftyJSON to map JSON to models. SwiftyJSON's role is to allow manipulating json data flexibly, but not map it onto an object. There are a ton of other libraries whose role is to do this, on top of my head: Unbox, ObjectMapper, Mapper, etc. Those are fully unit tested and are doing a much better job at this than what SwiftyJSON would provide.

I'm going to close this as a wontfix, let me know if you'd like to reopen.

@ldiqual ldiqual closed this as completed Nov 22, 2016
@eliburke
Copy link

Thumbs up for Unbox and Wrap which interoperate nicely with SwiftyJSON. Many of the other object mappers need raw JSON data/strings, but these two work well with the Arrays and Dictionaries that SwiftyJSON emits and ingests. It may be worth a shout out in the README.

@johndpope
Copy link

Please bump this library to the readme as people running their own diy mapping code it's waste of time.
https://github.com/JohnSundell/Wrap

@dimoreno
Copy link

Hi @AmitBhavsarIphone can you help me with this please
https://stackoverflow.com/questions/47419448/get-value-from-object-model-in-swift-3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

6 participants