我在 iOS 中使用Mantle框架来构建一个简单的 JSON 结构,如下所示:
{
"posts":
[
{
"postId": "123",
"title": "Travel plans",
"location": "Europe"
},
{
"postId": "456",
"title": "Vacation Photos",
"location": "Asia"
}
],
"updates": [
{
"friendId": "ABC123"
}
]
}
本质上,我只对"posts"
密钥感兴趣,并希望完全忽略"updates"
密钥。另外在"posts"
数组中我希望完全忽略这个"location"
键。以下是我设置 Mantle 模型的方法:
@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
这是我的MantlePosts
模型:
@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
最后,这是我加载要转换的 JSON 的方式:
- (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];
问题是,当我仅显式映射and时,我的后代数组MantlePosts
包含所有 3 个属性postId
、title
和。该数组被忽略,这是我想要的,但我一直无法忽略后代数组中的某些键。对此的任何帮助将不胜感激。location
postId
title
"updates"
这是我po
在控制台中响应时收到的示例。
(lldb) po posts
<MantlePosts: 0x6000000153c0> {
posts = (
{
location = Europe;
postId = 123;
title = "Travel plans";
},
{
location = Asia;
postId = 456;
title = "Vacation Photos";
}
);
}
(lldb)