带有数组映射的restkit嵌套对象

Posted

技术标签:

【中文标题】带有数组映射的restkit嵌套对象【英文标题】:restkit nested object with array mapping 【发布时间】:2014-03-11 21:43:28 【问题描述】:

我有这个 json:


    "status": "ok",
    "post": 
        "id": 171,
        "type": "locations",
        "slug": "plaza-404",
        "url": "http://localhost/?locations=plaza-404",
        "status": "publish",
        "title": "Sucursal Plaza 404",
        "title_plain": "Sucursal Plaza 404",
        "content": "",
        "excerpt": "",
        "date": "2014-03-05 19:59:50",
        "modified": "2014-03-07 19:11:43",
        "categories": [],
        "tags": [],
        "author": 
            "id": 1,
            "slug": "arturocalvo",
            "name": "arturocalvo",
            "first_name": "",
            "last_name": "",
            "nickname": "arturocalvo",
            "url": "",
            "description": ""
        ,
        "comments": [],
        "attachments": [],
        "comment_count": 0,
        "comment_status": "closed",
        "custom_fields": 
            "id": [
                "1"
            ],
            "location_id": [
                 "1"
            ],
            "calle": [
                "Av. Gomez Morin No.404  Local A3-5"
            ]

我只想映射名为“calle”的自定义字段的标题,这是我的位置界面

@interface Location : NSObject

@property (nonatomic, copy) NSString * name;
@property (nonatomic, copy) NSSet * calle;
@end

这是我的代码

RKObjectMapping *locationMapping = [RKObjectMapping mappingForClass:[Location class]];
RKObjectMapping *locationCustomMapping = [RKObjectMapping mappingForClass: [LocationCustom class]];

[locationMapping addAttributeMappingsFromDictionary:@
                                                      @"title": @"name",
                                                      @"calle": @"calle"
                                                      ];


RKResponseDescriptor *locationResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:locationMapping method:RKRequestMethodAny pathPattern:nil keyPath:@"post" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];

[objectManager addResponseDescriptor:locationResponseDescriptor];


NSURLRequest *request = [NSURLRequest requestWithURL:baseURL];
RKObjectRequestOperation *objectRequestOperation = [[RKObjectRequestOperation alloc]    initWithRequest:request responseDescriptors:@[ locationResponseDescriptor ]];

但由于某种原因我无法映射它,每次都得到一个空值,有人可以帮助我吗?

【问题讨论】:

【参考方案1】:

您在 JSON 中缺少一个级别,您需要告诉 RestKit 进行导航。使用:

@"custom_fields.calle": @"calle"

在您的映射中。

【讨论】:

非常感谢!!,我已经为此苦苦挣扎了大约 2 个小时,实际上没有尝试过 D:,这解决了我的问题,再次感谢。 没问题,欢迎栈溢出!请对有帮助的答案进行投票,并勾选您问题的正确答案:-)

以上是关于带有数组映射的restkit嵌套对象的主要内容,如果未能解决你的问题,请参考以下文章

Restkit 0.20 嵌套对象数组映射问题

RestKit:将嵌套数组映射到对象

RestKit .22:无法成功映射与嵌套 JSON 的关系

Restkit 映射复杂的嵌套数组

无法映射嵌套的 RestKit 对象

RestKit 0.20 嵌套对象映射(对象树的路径不同)