地幔:忽略数组内嵌套字典中的键

时间:2018-06-09 22:36:17

标签: ios objective-c json parsing mantle

我在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"键。以下是我设置地幔模型的方法:

@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];

问题是,当我仅显式映射MantlePosts时,postId的后代数组包含所有3个属性titlelocationpostIdtitle"updates"数组被忽略,这是我想要的,但我一直被困在能够忽略后代数组中的某些键。任何有关这方面的帮助将不胜感激。

以下是我在控制台中po响应时收到的内容示例。

(lldb) po posts
<MantlePosts: 0x6000000153c0> {
    posts =     (
                {
            location = Europe;
            postId = 123;
            title = "Travel plans";
        },
                {
            location = Asia;
            postId = 456;
            title = "Vacation Photos";
        }
    );
}

(lldb)

enter image description here

0 个答案:

没有答案