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

custom class for parsing NSArray #54

Closed pechn closed 8 years ago

pechn commented 8 years ago

Dears, Suppose I have the objects below:

@interface Author : NSObject
@property(nonatomic, strong) NSMutableArray *posts;
@end

@interface Post : NSObject
@property(nonatomic, strong) NSString *title;
@end

@interface AnotherPost : NSObject
@property(nonatomic, strong) NSString *title;
@end

And the dictionary data like:

{
    "posts": [
        {
            "title": "title 1"
        },
        {
            "title": "title 2"
        }
    ]
}

The statement below will deserialize Author object using Post class for parsing the array data.

Author *author = [Author objectFromDictionary:aDictionary];

My question is how can I configure AnotherPost class for parsing the array data instead of Post class?

It would be appreciate for you to give me some guides.

Thank you:)

aryaxt commented 8 years ago

if you want to have only AnotherPost in the array

[inCodeMappingProvider mapFromDictionaryKey:@"posts" toPropertyKey:@"posts" withObjectType:[AnotherPost class] forClass:[Author class]];

If you want to have both Post & AnotherPost in the array, you can use a transformer for a given key ("post" in this case) and manually map each object the way you want.

[mappingProvider mapFromDictionaryKey:@"posts" toPropertyKey:@"posts" forClass:[Author class] withTransformer:^id(id currentNode, id parentNode) {
    NSMutableArray *differentPosts = [NSMutableArray array];

    for (NSDictionary *dict in currentNode) {
        NSString *type = dict[@"type"];
        if ([type isEqualToString:@"post") { //logic to differentiate posts
              [differentPosts addObject:[Post objectFromDictionary:dict]];
        }
        else if ([type isEqualToString:@"another-post") { {
            [differentPosts addObject:[AnotherPost objectFromDictionary:dict]];
        }
     }

     return differentPosts;
}];

Let me know if this works

pechn commented 8 years ago

@aryaxt Yes, it works well! Thank you very much:)