1
votes

I receive JSON objects like this:

{
  "rent": {
    "id": "someId"
  },
  "upcoming": {
    "id": "someId"
  },
  "watchnow": {
    "id": "someId"
  }
}

I then set forceCollectionMapping to YES on my mapping to get one object for each key, i.e. one object for "rent", one for "upcoming" and one for "watchnow". Specifically this is done with this code:

[searchResultsMapping addAttributeMappingFromKeyOfRepresentationToAttribute:@"searchSection"];

So this succesfully gives me three objects for which I can then do some relationship mapping to get the id keys and what ever else is on the object.

Now, my problem is that if an error occurs, I get this JSON code:

{
  "error": {
    "errorcode": "someId"
  }
}

So (searchSection) becomes "error" and my relationship mapping looks for "id" but it's not there so the mapping fails. The problem is that setting addAttributeMappingFromKeyOfRepresentationToAttribute makes RestKit try to make an object from every single key, and I can't expect every key to be relevant and useful for my mappings. Can I do anything about this?

2

2 Answers

1
votes

You have a couple of options:

  1. Use an RKDynamicMapping as the root mapping for your response descriptor
  2. Use multiple response descriptors to specify exactly which keypaths to process
  3. Use KVC validation to reject the error mapping (not ideal as the error isn't really captured)

For the dynamic mapping option, the dynamic mapping has the forceCollectionMapping option set and it checks the top level key available and returns the appropriate mapping (which wouldn't have forceCollectionMapping set and which uses addAttributeMappingFromKeyOfRepresentationToAttribute:).

0
votes

I got it to work using Wain's first suggestion. Here's the solution if anyone has the same issue:

I created a dynamic mapping like this:

RKDynamicMapping *dynamicMapping = [RKDynamicMapping new];
dynamicMapping.forceCollectionMapping = YES;
[dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping * (id representation) {
    if ([representation valueForKey:@"watchnow"] || [representation valueForKey:@"upcoming"] || [representation valueForKey:@"rent"]) {
        return searchResultsMapping;
    }
    return nil;
}];

As you can see in my example at the top, I'm only interested in keys named "watchnow", "upcoming" or "rent".

The searchResultsMapping which is returned is configured like this:

RKObjectMapping *searchResultsMapping = [RKObjectMapping mappingForClass:[TDXSearchResults class]];
[searchResultsMapping addAttributeMappingFromKeyOfRepresentationToAttribute:@"searchSection"];

So I now end up with three SearchResult objects with either "watchnow", "upcoming" or "rent" in their searchSection NSString property.