aryaxt / OCMapper

Objective-C library to easily map NSDictionary to model objects, works perfectly with Alamofire. ObjectMapper works similar to GSON
MIT License
347 stars 45 forks source link

Feature Request: Can OCMapper figure out the property/var type automatically? #49

Open jpage4500 opened 8 years ago

jpage4500 commented 8 years ago

Right now we're using mapFromDictionaryKey() to map a variable to the class type which works fairly well. But, as I remember in Android GSON will automatically detect the type and just parse it using that class.

Just curious - is there a way OCMapper can figure this out itself?

ie: any way OCMapper could figure out that homeTeam variable is of class type GameStatusTeam and not require the mapping below?

    var homeTeam: GameStatusTeam?

...

        mapper().mapFromDictionaryKey("homeTeam", toPropertyKey:"homeTeam", withObjectType:GameStatusTeam.self, forClass:GameStatus.self);
aryaxt commented 8 years ago

Hey @jpage4500

Does it not work? mapping for properties should work automatically as long as they key in dictionary matches the property name. https://github.com/aryaxt/OCMapper/blob/master/OCMapperTests/ObjectMapperTests.m#L75

The only exception would be for arrays ex: "homeTeams" would map to "homeTeams" as long as the class name is "homeTeams" or "homeTeam" ex: "homeTeams" would NOT map to "homeTeams" if the class name is "Team"

For mapping arrays, ObjectMapper finds an appropriate class based on property name (singular, plural name) instead of using reflection (runtime API doesn't give you the type of objects in the array)

jpage4500 commented 8 years ago

Hi @aryaxt - it doesn't seem to work all of the time for me. For example, after receiving your update I commented out a few mappings to test. The first one worked but others failed to parse - giving lots of errors in the log.

I did notice 1 thing that's different in my code than what I originally stated.. the server returns "home_team" and my property is called "homeTeam".

I know OCMapper automatically handles this since it's working in lots of other places for me. But, could there be an issue when OCMapper needs to do both: 1) convert case 2) determine class type

Here's what I have below (which works) - but if I comment out the mapping it fails.

    var homeTeam: GameStatusTeam?
...
        mapper().mapFromDictionaryKey("home_team", toPropertyKey:"homeTeam", withObjectType:GameStatusTeam.self, forClass:GameStatus.self);

Sorry, I should have also mentioned I have a simple mapper() function to get the singleton:

    class func mapper() -> InCodeMappingProvider {
        return ObjectMapper.sharedInstance().mappingProvider as! InCodeMappingProvider
    }
aryaxt commented 8 years ago

hmm are you able to write a failing test?

screen shot 2016-04-19 at 9 14 46 am

@interface User : NSObject
@property (nonatomic, strong) Address *homeAddress;
@end