I have some json data that looks something like this:
{
items: [
{ // object 1
aProperty: "aValue",
anotherProperty: "anotherValue",
anObjectProperty: {}
},
{ //object 2
aProperty: "aValue",
anotherProperty: "anotherValue",
anObjectProperty: {}
}
]
}
I want to map this json into an array of two objects using Mantle.
This would look like the following:
@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 the json, then parse what is inside of that key.
Instead, I want Mantle to just map the whole 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's is all set and done, this will leave me this something like the following
NSArray *myArrayOfObjects = (MyObjects*)myobjects.items;
This is all great, but i believe the creation of a "MyObjects" class, just to be a placeholder for an array of MyObject is overkill. Is there a better solution? Ideally, I'm looking for a setting in mantle (or something that's easier than creating two classes just to get an array of objects) that handles the root "item" key for me, so that when this parses, it just comes out as an array of 2 objects.
Thanks!
In the place where we map Jsonobject in MTLJSONAdapter
if, the json is of object type, the object should be mapped as
object = [MTLJSONAdapter modelOfClass:responseType fromJSONDictionary:jsonObject error:&error];
if the json is of array type, the object should be mapped as
object = [MTLJSONAdapter modelsOfClass:responseType fromJSONArray:jsonObject error:&error];
[
{
{ // object 1
aProperty: "aValue",
anotherProperty: "anotherValue",
anObjectProperty: {}
},
{ //object 2
aProperty: "aValue",
anotherProperty: "anotherValue",
anObjectProperty: {}
}
}
{
{ // object 1
aProperty: “bValue",
anotherProperty: "anotherValue",
anObjectProperty: {}
},
{ //object 2
aProperty: “bValue",
anotherProperty: "anotherValue",
anObjectProperty: {}
}
}
]
if this is the case, it can be mapped like this
object = [MTLJSONAdapter modelsOfClass:responseType fromJSONArray:jsonObject error:&error];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With