iosgithub-mantle

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?


Solution

  • 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.