evermeer / AlamofireJsonToObjects

An Alamofire extension which converts JSON response data into swift objects using EVReflection
Other
161 stars 28 forks source link

get Array with key #27

Closed daniaDlbani closed 8 years ago

daniaDlbani commented 8 years ago

my server returns a response like this

{data:[array of EVObject]}

How can i get those kind of data?

I have tried Alamofire.request(.GET, URL) .responseArray("data", completionHandler: (Result<[EVObject], NSError>) -> Void in) but it gives me a compile error

Cannot invoke 'responseArray' with an argument list of type '(String, completionHandler: (Result<[EVObject], NSError>).Type)'

evermeer commented 8 years ago

EVObject itself does not have any properties. You would need a container objects like you see in the code below. Besides that the root is an object with a data property and not an array. You can find sample code here: https://github.com/evermeer/AlamofireJsonToObjects/blob/ae46e82611e7ed18c04ba8b09d2f76e90f688d55/AlamofireJsonToObjectsTests/AlamofireJsonToObjectsTests.swift#L72-L72

class myData: EVObject {
   var data: [myItem]
}

class myItem: EVObject {
   var someField: String?
}

Alamofire.request(.GET, URL)
                .responseObject { (request: NSURLRequest?, HTTPURLResponse: NSHTTPURLResponse?, response: Result< myData, NSError>) in
 // Do something with the response
}
daniaDlbani commented 8 years ago

thanks for the fast reply, I am not using EVObject directly I mean a subclass of it, although the data object is in all API responses so in this case I should incapsulate all My model to have super model with data property

evermeer commented 8 years ago

Yes, And you only need 1 super model for the data property if you are using a base class for that. You do have to implement the getSpecificType method in that base class. You can find sample code for that here: https://github.com/evermeer/EVReflection/blob/master/EVReflection/EVReflectionTests/EVRelfectionEnheritanceTests.swift#L83

An other way to do this is by using generics. I think it's actueally a bit nicer. Sample code for that can be found here: https://github.com/evermeer/EVReflection/blob/master/EVReflection/EVReflectionTests/EVReflectionWorkaroundSwiftGenericsTests.swift#L97 And here is the test for that: https://github.com/evermeer/EVReflection/blob/master/EVReflection/EVReflectionTests/EVReflectionWorkaroundSwiftGenericsTests.swift#L59 And here is a nice sample code where the object is using generics but also the service call is created using generics: https://github.com/evermeer/AlamofireJsonToObjects/blob/master/AlamofireJsonToObjectsTests/NestedGenericsIssue25.swift#L25