I am using the Mantle framework in iOS for a simple JSON structure that looks like this:
{
"posts":
[
{
"postId": "123",
"title": "Travel plans",
"location": "Europe"
},
{
"postId": "456",
"title": "Vacation Photos",
"location": "Asia"
}
],
"updates": [
{
"friendId": "ABC123"
}
]
}
Essentially I am only interested in the "posts"
key and wish to completely ignore the "updates"
key. Additionally within the "posts"
array I wish to completely ignore the "location"
key. Here is how I set up my Mantle Models:
@interface MantlePost: MTLModel <MTLJSONSerializing>
@property (nonatomic, strong) NSString *postId;
@property (nonatomic, strong) NSString *title;
@end
@implementation MantlePost
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
return @{
@"postId": @"postId",
@"title": @"title",
};
}
@end
And here is my MantlePosts
model:
@interface MantlePosts: MTLModel<MTLJSONSerializing>
@property (nonatomic, strong) NSArray<MantlePost *> *posts;
@end
@implementation MantlePosts
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
return @{
@"posts": @"posts"
};
}
+ (NSValueTransformer *)listOfPosts {
return [MTLJSONAdapter arrayTransformerWithModelClass:MantlePost.class];
}
@end
Finally, here is how I load my JSON up to be converted:
- (NSDictionary *)loadJSONFromFile {
NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"parse-response" ofType:@"json"];
NSError *error = nil;
NSData *jsonData = [[NSString stringWithContentsOfFile:jsonPath usedEncoding:nil error:&error] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];
return jsonDict;
}
NSError = nil;
NSDictionary *jsonData = [self loadJSONFromFile];
MantlePosts *posts = (MantlePosts *)[MTLJSONAdapter modelOfClass:MantlePosts.class fromJSONDictionary:jsonData error:&error];
The problem is, my descendent array of MantlePosts
contains all 3 properties postId
, title
, and location
, when I explicitly mapped only postId
and title
. The "updates"
array is ignored which is what I wanted but I've been stuck being able to ignore certain keys in the descendent arrays. Any help on this would be appreciated.
Here is an example of what I receive when i po
the response in the console.
(lldb) po posts
<MantlePosts: 0x6000000153c0> {
posts = (
{
location = Europe;
postId = 123;
title = "Travel plans";
},
{
location = Asia;
postId = 456;
title = "Vacation Photos";
}
);
}
(lldb)