1

我正在尝试使用 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 键控的对象,所以我不确定应该如何将它映射到我的SBShow类中,定义如下:

#import <Foundation/Foundation.h>
#import <Mantle.h>

@interface SBShow : MTLModel <MTLJSONSerializing>

@property (nonatomic, strong) NSNumber *tvdbid;
@property (nonatomic, strong) NSString *showName;
@property (nonatomic, strong) NSString *network;
@property (nonatomic, strong) NSString *status;

@end

@implementation SBShow

+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    return @{@"showName": @"show_name"};
}

+ (NSValueTransformer *)dateJSONTransformer {

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];

    return [MTLValueTransformer reversibleTransformerWithForwardBlock:^(NSString *str) {
        return [formatter dateFromString:str];
    } reverseBlock:^(NSDate *date) {
        return [formatter stringFromDate:date];
    }];
}

@end

任何帮助将不胜感激。

4

1 回答 1

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);

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

于 2014-06-21T18:49:21.617 回答