RestKit对象映射 - 一个实体,两个映射

时间:2012-03-26 21:22:48

标签: iphone core-data mapping restkit

在我的last question was solved之后,我从服务器收到的JSON更改为以下内容,我无法处理映射以使用Core Data保存数据。

实体

 Key 
 - alias 
 - key
 - keyType
 - keyword
 - unid
 - until

JSON(来自服务器)

{
    "documents": 1026,
    "configuration": 
    {
        ...
    },
    "data": 
    [
        {
            "alias": "",
            "key": "SALUTATION",
            "keyType": "S",
            "keyword": "Mr",
            "unid": ""
        },
        ...
        {
            "alias": "Automobile",
            "key": "ACCOUNT_MARKET_SEGMENT",
            "keyType": "A",
            "keyword": "Automobile",
            "unid": ""
        }
    ],
    "documentsFound": 770,
    "maxCount": -1,
    "since": "20120326200001",
    "until": "20120326211309"
}

现在我想映射“数据”中的所有数据以及实体“密钥”的关键字“直到”,但无法找到正确的解决方案。到目前为止,我获取数据的映射看起来像这样并且运行良好但当然错过了“直到”键。

RKManagedObjectMapping* keyMapping = [RKManagedObjectMapping mappingForClass:[Key class]];
keyMapping.rootKeyPath = @"data";
[keyMapping mapKeyPath:@"key" toAttribute:@"key"];
[keyMapping mapKeyPath:@"keyword" toAttribute:@"keywordEN"];
[keyMapping mapKeyPath:@"alias" toAttribute:@"alias"];
keyMapping.setDefaultValueForMissingAttributes = YES;

感谢您的想法!

1 个答案:

答案 0 :(得分:2)

您可能想要进行两次映射。第一个映射将包含整个对象,并与嵌套的“数据”路径有关系。

RKObjectMapping *keyMapping = [RKObjectMapping mappingForClass:[Key class]];
[keyMapping mapAttributes:@"alias", @"key", nil];
[keyMapping mapKeyPath:@"keyword" toAttribute:@"keywordEN"];

RKObjectMapping *outerMapping = [RKObjectMapping mappingForClass:[Container class]];
[outerMapping mapKeyPath:@"data" toRelationship:@"keys" withMapping:keyMapping];
[outerMapping mapAttributes:@"since", @"until", "maxCount", "documentsFound", nil];

这将为您提供一个包含元数据的新对象,然后是容器的keys属性上的一组关键对象。您可以在0.9.4开发分支上使用基于resourcePath的映射注册(即将发布),而不是使用rootKeyPath。