RestKit JSON元数据的响应描述符

时间:2014-11-20 17:56:26

标签: ios objective-c json restkit restkit-0.20

我有一个JSON响应,它返回一个对象列表,还有一个时间戳值为" MetaData"。响应看起来像这样 -

{
  "access_time": 1416467865510,
  "profiles" : [
    {
        "user_id": "bbb91ae431b",
        "email": "bob@foo.corp",
        "first_name": "Bob",
        "last_name": "Burroughs",
        "primary_phone": "16507001212"
    },
    {
        "user_id": "ddd8d8d8d8d",
        "email": "don@foo.corp",
        "first_name": "Don",
        "last_name": "Darko",
        "primary_phone": "14154001212"
    }
  ]
}

我的RestKit描述符代码看起来像这样。这工作得很好,我得到了所有的对象。

RKEntityMapping *contactMapping = [RKEntityMapping mappingForEntityForName:@"Contact" inManagedObjectStore: managedObjectStore];
[contactMapping addAttributeMappingsFromDictionary:@{
                                                   @"user_id" : @"userId",
                                                   @"email" : @"email",
                                                   @"first_name" : @"firstName",
                                                   @"last_name" : @"lastName",
                                                   @"primary_phone" : @"primaryPhone"
                                                   }];
contactMapping.identificationAttributes = @[@"userId"];
RKResponseDescriptor *contactResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:contactMapping method:RKRequestMethodAny pathPattern:nil keyPath:@"profiles" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];

以上的事情适合我。 但是,我也希望能够访问上面的access_time字段。我如何获得访问权限?我正在考虑将该值存储在NSUserDefaults中以供以后使用,因为它不是属于User / Contact对象的字段。我该怎么做?

2 个答案:

答案 0 :(得分:2)

试试这个:

[contactMapping addAttributeMappingsFromDictionary:@{
                                               @"user_id" : @"userId",
                                               @"email" : @"email",
                                               @"first_name" : @"firstName",
                                               @"last_name" : @"lastName",
                                               @"primary_phone" : @"primaryPhone",
                                               @"@parent.access_time" : @"accessTime",
                                               }];

您可以阅读更多here

答案 1 :(得分:0)

您可以使用RKRelationshipMapping在父JSON对象(包含“access_time”)和子“profiles”对象之间创建关系。

然后,您不必让您的响应描述符直接访问keyPath:@"profiles",而是将其设置为keyPath:nil并访问整个JSON对象,包括access_time和关联的配置文件。

您还需要确保父JSON对象具有相应的实体和关系(在数据模型中)(您可以随意调用它)。然后返回带有RestKit映射的文件,使用addPropertyMappingsFromArray:将关系添加到父映射对象。

然后,一旦返回请求,您就可以通过简单的迭代遍历父JSON的关联概要文件对象(假设您有XCode创建关联的NSManagedObject子类):

// allObjects returns an NSArray representation of the NSSet
NSArray *profiles = [[parentObject valueForKeyPath:@"profiles"] allObjects];

希望这有帮助。