7

以下のネストされたjsonをRestKit RKObjectMappingでマップするにはどうすればよいですか? 「データ」をマッピングするだけです。以下の私の現在のコードは (null) を返します - ありがとう!

{

    "sucess": true,
    "error": {
        "code": "",
        "message": ""
    },
    "data": [
        {
            "id": 1,
            "name": "Salad",
            "description": "Salad Desc",
            "category_id": 1
        },
        {
            "id": 2,
            "name": "Soup",
            "description": "Soup Desc",
            "category_id": 1
        },
        {
            "id": 3,
            "name": "Wrap",
            "description": "Wrap Desc",
            "category_id": 1
        },
        {
            "id": 4,
            "name": "Appetizers",
            "description": "Appetizers Desc",
            "category_id": 1
        }
    ]

} 

クラス

@interface Subcategory : NSObject    
    @property (nonatomic, retain) NSNumber *subcategoryID;
    @property (nonatomic, retain) NSNumber *categoryID;
    @property (nonatomic, retain) NSString *name;
    @property (nonatomic, retain) NSString *description;
    @property (nonatomic, retain) NSString *thumbnail;
    @property (nonatomic, retain) NSArray *data;

ViewController

RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[Subcategory class]];

RKObjectMapping* dataMapping = [RKObjectMapping mappingForClass:[Subcategory class]];
[dataMapping mapKeyPath:@"id" toAttribute:@"subcategoryID"];
[dataMapping mapKeyPath:@"category_id" toAttribute:@"categoryID"];
[dataMapping mapAttributes:@"name", @"description", nil];

[mapping mapKeyPath:@"data" toRelationship:@"data" withMapping:dataMapping];

[[RKObjectManager sharedManager] loadObjectsAtResourcePath:[NSString stringWith
4

1 に答える 1

6

rootKeyPath が欠落しており、プロバイダーでマッピングも設定しています。

RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[Subcategory class]];    
RKObjectMapping* dataMapping = [RKObjectMapping mappingForClass:[Subcategory class]];
[dataMapping mapKeyPath:@"id" toAttribute:@"subcategoryID"];
[dataMapping mapKeyPath:@"category_id" toAttribute:@"categoryID"];
[dataMapping mapAttributes:@"name", @"description", nil];
dataMapping.rootKeyPath = @"data"; //this is what you were missing    
//get your  mapping provider (i'm not sure if you already have on declared)
[mappingProvider setObjectMapping:dataMapping forResourcePathPattern:@"/somepath/toservice/"];
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/somepath/toservice/"];

他の要素 (「エラー」など) へのアクセスに関する質問に答える詳細情報は次のとおりです。

- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error {
    NSError *parseError = nil;
    id response = [objectLoader.response parsedBody:&parseError];
    DLog(@"response %@", response);    
    if (!parseError) {
        NSString *errorMessage = [[response valueForKey:@"error"] valueForKey:@"message"];     
        //do something with it    
    }
}
于 2012-04-24T16:40:01.997 に答える