I have some json data that look something like this:
{ items: [ { // object 1 aProperty: "aValue", anotherProperty: "anotherValue", anObjectProperty: {} }, { //object 2 aProperty: "aValue", anotherProperty: "anotherValue", anObjectProperty: {} } ] }
I want to map this json to an array of two objects using Mantle.
It will look like this:
@interface MyObject : MTLModel <MTLJSONSerializing> @property (nonatomic, strong) NSString *myProperty; @property (nonatomic, strong) NSString *anotherProperty; @property (nonatomic, strong) NSObject *anObject; @end @implementation MyObject + (NSDictionary *)JSONKeyPathsByPropertyKey { return @{ @"myProperty": @"myProperty", @"anotherProperty" : @"anotherProperty", @"anObject": @"anObject" }; } @end
However, this would require me to go and find the "items" key in json, then analyze what is inside this key.
Instead, I want the Mantle to simply display the entire object for me. So, I came up with this solution:
@interface MyObjects : MTLModel <MTLJSONSerializing> @property (nonatomic) NSArray *items; @end @implementation MyObjects + (NSDictionary *)JSONKeyPathsByPropertyKey { return @{ @"items": @"items" }; } + (NSValueTransformer *)itemsJSONTransformer { return [NSValueTransformer mtl_JSONArrayTransformerWithModelClass:[MyObject class]]; } @end
When everything is installed and done, it will leave me something like this:
NSArray *myArrayOfObjects = (MyObjects*)myobjects.items;
This is all great, but I believe that creating the "MyObjects" class, just to be a placeholder for the MyObject array, is redundant. Is there a better solution? Ideally, I'm looking for a setting in the mantle (or something that is simpler than creating two classes to get an array of objects) that processes the "item" key for me, so when it parses, it just appears as an array from 2 objects.
Thanks!