RestKit additional data in response

2019-08-30 22:08发布

问题:

I am using RestKit for mapping data from my api to CoreData entities and i wonder how can i get additional data from response. For example my api return structure like:

{
    "items": [
        {
            "id": 1,
            "title": "Title"
        },
        {
            "id": 2,
            "title": "Title 2"
        }
    ],
    "someParameter": "someValue"
}

i already have right mappings for shared object manager so i just send request:

[[RKObjectManager sharedManager] getObjectsAtPath:@"_api/items"
                                       parameters:parameters
                                          success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                                              //handle success
                                          }
                                          failure:^(RKObjectRequestOperation *operation, NSError *error) {
                                              //handle error
                                          }];

How can i get someParameter value in success block? Is this possible?

回答1:

You will need to tweak your mapping slightly. If you changed it as follows you should be able to get RESTkit to parse the 'someParameter' attribute for you. You need to have two classes (Parent and Child).

The Parent class has 2 attributes (someParameter and an array of Child objects). The addRelationshipMappingWithSourceKeyPath is what ties the Parent and Child object mappings together.

Code:

RKObjectMapping *parentMapping = [RKObjectMapping mappingForClass:[Parent class]];
[beaconActionMapping addAttributeMappingsFromDictionary:@{
                                                          @"someParameter" : @"someParameter"
                                                         }];


RKObjectMapping *childMapping = [RKObjectMapping mappingForClass:[Child class]];
[beaconMapping addAttributeMappingsFromDictionary:@{
                                                  @"id" : @"childId",
                                                  @"title" : @"title"
                                                  }];


[parentMapping addRelationshipMappingWithSourceKeyPath:@"items" mapping:childMapping];

Class hierarchy:

@interface Parent : NSObject
@property(nonatomic,strong) NSString *someParameter;
@property(nonatomic,strong) NSArray *items;  // Array of Child objects
@end

@interface Child : NSObject
@property(nonatomic,strong) NSString *childId;
@property(nonatomic,strong) NSString *title
@end


回答2:

You can add an additional response descriptor with a key path of someParameter. You can use that with a nil key path mapping to extract the string value into an object of your choice (usually a custom class).