objective-c – RestKit RKObjectMapping嵌套json

前端之家收集整理的这篇文章主要介绍了objective-c – RestKit RKObjectMapping嵌套json前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何使用RestKit RKObjectMapping映射下面的嵌套json?我只需要映射“数据”.我当前的代码返回(null) – 谢谢!
{

    "sucess": true,"error": {
        "code": "","message": ""
    },"data": [
        {
            "id": 1,"name": "Salad","description": "Salad Desc","category_id": 1
        },{
            "id": 2,"name": "Soup","description": "Soup Desc",{
            "id": 3,"name": "Wrap","description": "Wrap Desc",{
            "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;

视图控制器

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

解决方法

您缺少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",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    
    }
}

猜你在找的C&C++相关文章