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?
Asked
Active
Viewed 2,611 times
6
-
1possible duplicate of [How to specify child objects type in an NSArray with Mantle](http://stackoverflow.com/questions/13883693/how-to-specify-child-objects-type-in-an-nsarray-with-mantle) – David Snabel-Caunt Sep 17 '13 at 14:55
1 Answers
12
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.

sosale151
- 360
- 2
- 4
- 19

akashivskyy
- 44,342
- 16
- 106
- 116
-
1This fails if assignee field is empty/null. How can I check that and skip transformation in this case? – Borut Tomazin Oct 06 '14 at 12:05