使用带有Sickbeard API的Mantle

时间:2014-06-17 12:01:41

标签: objective-c github-mantle

我试图通过Mantle将Sickbeard API的响应映射到我的对象,但我无法弄清楚如何,因为响应是基于键值使用TVDB id作为关键,像这样:

"data": {
    "71663": {
        "air_by_date": 0, 
        "cache": {
            "banner": 1, 
            "poster": 1
        }, 
        "language": "en", 
        "network": "FOX", 
        "next_ep_airdate": "2014-09-28", 
        "paused": 0, 
        "quality": "Any", 
        "show_name": "The Simpsons", 
        "status": "Continuing", 
        "tvdbid": 71663, 
        "tvrage_id": 6190, 
        "tvrage_name": "The Simpsons"
    }, 
    "72227": {
        "air_by_date": 0, 
        "cache": {
            "banner": 1, 
            "poster": 1
        }, 
        "language": "en", 
        "network": "CBS", 
        "next_ep_airdate": "", 
        "paused": 0, 
        "quality": "Any", 
        "show_name": "Two and a Half Men", 
        "status": "Continuing", 
        "tvdbid": 72227, 
        "tvrage_id": 6454, 
        "tvrage_name": "Two and a Half Men"
    }
}

由于data对象不仅包含像[{"key": value},{"key": value}]这样的对象数组,而是包含一些唯一ID键入的对象,因此我不确定应该如何将其映射到我的{ {1}}类,定义如下:

SBShow

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您可以这样做,方法是将密钥添加到“JSON词典”的其余部分:

NSMutableArray *shows = [NSMutableArray array];
// data is an NSDictionary, representing the 'data' key in the JSON
[data enumerateKeysAndObjectsUsingBlock:^(NSString *tvdbID, NSDictionary *showData, BOOL *stop) {
    NSMutableDictionary *modelDictionary = [showData mutableCopy];
    modelDictionary[@"tvdbid"] = tvdbID;
    NSError *error = nil;
    SBShow *show = [MTLJSONAdapter modelOfClass:SBShow.class 
                             fromJSONDictionary:modelDictionary 
                                          error:&error];
    [shows addObject:show];
}];

NSLog(@"Show models are %@", shows);

您可以编写自己的转换器来封装此逻辑,并在适当时将其应用于数据密钥。