Json with field of string(containing a string of JSON) crashes when Restkit tries to map it

143 Views Asked by At

I am sending a json blob wrapped in a iron mq message.

It comes to Restkit as a:

{
id:"2837409187409328",
delay:60,
body:"{ myJson:{ "hey":true}}"
}

Im using a rkrelationship to map a child object with the body: as type CustomObject.

However when Restkit tries to map to that custom object it blows up because it views that 'body' as a NSString instead of NSDictionary and tries to get the value out of the resulting sourceObject by using the sourceKeyPath... but since its a NSString it blows up. With:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x7fcf91165060> valueForUndefinedKey:]: this class is not key value coding-compliant for the key alreadyLiked.'

I have tried to use dynamic mapping and replace the representation with an NSDictionary.

I have tried doing validate on the accessors as is suggested in the docs, but that code is never called. Any ideas?

1

There are 1 best solutions below

0
On

Solved with post processing. I ended up taking the string that was passed into the body, overriding the setter for that body property, and in that setter running a mapping operation to take the string of json, and map it to my custom object (after converting to a dictionary) then setting that on my parent object.

Hope this helps you!

//here I have an object with a string property called Body that contains JSON.
//I extract the json, turn it into a dictionary then map it to another property on that same object that actually has a relationship mapping...
//always check to see if the body actually exists before you try to map it 
//otherwise you will have a crash in your overridden setter..
if(self.Body){
        NSData *data = [self.Body dataUsingEncoding:NSUTF8StringEncoding];
        id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

        NSDictionary *representation = json;
        //NSDictionary *metadata = @{ @"URL": [NSURL URLWithString:@"http://restkit.org"]http://restkit.org"] };

        RKObjectMapping *objectMapping = [MyObject mapping];

        RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:representation destinationObject:mappedResultDTO mapping:objectMapping];

        RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new];
        operation.dataSource = dataSource;
        // [operation start];

        NSError *error = nil;
        BOOL success = [operation performMapping:&error];
    }