0
votes

I am getting a json document like this from a ws:

{
   ...
   error=true,
   errorMsg="xyz",
   errorCode="1234"
}

But these attributes are optional so sometimes they are present and sometime they are not.

I added a dynamic mapping for reading only error - only if error is set to true

either:

[dynamicMapping addMatcher:[RKObjectMappingMatcher matcherWithKeyPath:@"error" expectedValue:[NSNumber numberWithInt:1] objectMapping:errorMapping]];

or

[dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) {
        if ([[representation valueForKey:@"error"] isEqualToNumber:[NSNumber numberWithInt:1]]) {
            return errorMapping;
        } 

        return nil;
    }];

Everything is working fine if error=true but if the error attributes are missing I get a warning:

restkit.object_mapping:RKMapperOperation.m:98 Adding mapping error: Could not find an object mapping for keyPath: '<null>'

I just want to get rid of the warning. What is the best practice for this problem? How do I mark the attribute as optional?

1
Are you using this and another mapping? - Wain
Hi, yes I use the same mapping ("errorMapping") for server errors with status code RKStatusCodeClassServerError = 500. So if an error occurs on the server the server send the error msg in a json format. - cloudnaut
I mean how is your success scenario handled? Usually your dynamic mapping would check the status and then either return the error mapping or the success mapping. - Wain
A success would be if either error=false or no error attributes are specified. Error=false with a message would be a warning for which I may also add an object and add another dynamic mapping. - cloudnaut

1 Answers

0
votes

To remove the warning, you need to complete your mapping configuration, because currently you're only giving it information for half of the scenarios. The warning is just that, a warning. It may be that it is intended functionality, that's why it isn't an assertion.

So, you're handling the error situation, simply add another check, something like:

[dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) {
    NSNumber *errorNumber = [representation valueForKey:@"error"];

    if (errorNumber == nil) {
        return successMapping;
    } else if ([errorNumber isEqualToNumber:[NSNumber numberWithInt:1]]) {
        return errorMapping;
    } 

    return warningMapping;
}];

Also, you aren't limited to checking just the 'error' parameter. You can check any other key and value in the response, both for existence and for value.