tristanhimmelman / AlamofireObjectMapper

An Alamofire extension which converts JSON response data into swift objects using ObjectMapper
MIT License
2.66k stars 474 forks source link

How to work with a mixed JSON? #106

Closed mayckonx closed 8 years ago

mayckonx commented 8 years ago

I'am tryting to work with a Mixed JSON, but I don't know how to do it.

For example, when the user will do login, the service will return multiple data(orders,news,requests of the user, each one of them in a key, like below).

{ "status": 1, "debug": "retornando sem data de atualização", "news": [{ "id": 10, "titulo": "Miss", "resumo": "Dolorum libero dolorem assumenda dignissimos quibusdam sint. Ipsa non harum eveniet deleniti aspernatur non. Accusamus rerum quas non et exercitationem enim ea. Eaque et modi est nesciunt quis ut.", "dtnoticia": "2002-09-25", "descricao": "Rerum laudantium dolores et. Sint asperiores qui laboriosam omnis at. Voluptates nisi quaerat in aperiam est. Aspernatur dolorum odio quaerat veritatis totam.", "created_at": "2016-05-23 14:03:00", "updated_at": "2016-05-23 14:03:00" }], "orders": [{ "id": 10, "value": 50, "iduser": 10 }], "user": { "id": 10, "name": "Elton", "type": 1 } }

But news doesn't have relation with orders. How can I proceed from here to work with mixed json? Alamofire.request(.POST, Constants.WEBSERVICE_URL+Constants.SERVICE_NEWS+"obter_noticias", parameters: parameters).responseArray { (response: Response<[News], NSError>) in print(response.request) // original URL request print(response.result.value) // server data

And for the last, in my JSON, I always return "debug" and "status" to certificate that everything is OK. I don't know have idea how integrate AlamofireObjectMapper with my way of work.

:(

tristanhimmelman commented 8 years ago

You can create a Response object that holds all the types of information that you need to handle your login request. It could look something like this:

class LoginResponse: Mappable {

    var news: [News]?
    var orders: [Orders]?
    /// etc

    required init?(_ map: Map){

    }

    func mapping(map: Map) {
        news <- map["news"]
        orders <- map["orders"]
    }
}
Alamofire.request(.GET, LOGIN_URL, parameters: parameters).resposneObject { (response: Response<LoginResponse, NSError>) in

}