Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MTLModels within MTLModels?

I have a web service that returns a JSON of an object, and within that object there is a list of other objects. How can I get Mantle to create an object for each one of these nested objects, rather than giving me a dictionary for each one of them?

like image 386
meisel Avatar asked Jul 14 '13 05:07

meisel


1 Answers

This can be done using mtl_JSONDictionaryTransformerWithModelClass: tranformer introduced by Mantle some time ago.

Let's look at the example taken from Mantle project readme itself:

@interface GHIssue : MTLModel <MTLJSONSerializing>

@property (nonatomic, strong, readonly) GHUser *assignee;

@end
@implementation GHIssue

+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    return @{
        @"assignee": @"assignee",
    };
}

+ (NSValueTransformer *)assigneeJSONTransformer {
    return [NSValueTransformer mtl_JSONDictionaryTransformerWithModelClass:[GHUser class]];
}

@end

Assuming GHUser is a subclass of MTLModel conforming to MTLJSONSerializing protocol, everything should work perfectly.

UPDATE: The above solution is now deprecated. The correct method to use now would be

return [MTLJSONAdapter dictionaryTransformerWithModelClass:GHUser.class];

inside the 'assigneeJSONTransformer' method.

like image 183
akashivskyy Avatar answered Nov 11 '22 03:11

akashivskyy