Search code examples
iphoneioscore-datarestkit

Manually load objects using RestKit into Core Data using JSON string


Using the development branch of restkit (0.20), is there a way to perform mapping on a JSON string into the core data object store?

I know in 0.10, the method described at the bottom of this page worked but how is this operation performed in restkit 0.20? Any guidance appreciated! Thanks!

id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:MIMEType];
id parsedData = [parser objectFromString:JSONString error:&error];

RKObjectMappingProvider* mappingProvider = [RKObjectManager sharedManager].mappingProvider;
RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:parsedData mappingProvider:mappingProvider];
RKObjectMappingResult* result = [mapper performMapping];

Solution

  • I installed RESTKit v0.20.0pre4 yesterday and had the same need for one particular case.

    Here is an example of the JSON String I want to map:

    {"info":"the sun is shining","detail":"in Bordeaux ~ 29 °C"}
    

    This is how I perform the mapping.

    - (InfoRESTMapped *)mapInfoFromJSONString:(NSString *) JSONString{
    
    NSString* MIMEType = @"application/json";
    NSError* error;
    
    NSData *data = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    id parsedData = [RKMIMETypeSerialization objectFromData:data MIMEType:MIMEType error:&error];
    if (parsedData == nil && error) {
        //deal with error
    }
    
    RKObjectMapping *infoMapping = [RKObjectMapping requestMapping];
    [infoMapping addAttributeMappingsFromDictionary:@{
     @"info": @"myInfo",
     @"detail": @"myDetail",
     }];
    
    
    InfoRESTMapped *infoMapped = [[InfoRESTMapped alloc] init];
    RKMappingOperation* mapper = [[RKMappingOperation alloc] initWithSourceObject:parsedData destinationObject:infoMapped mapping:infoMapping];
    [mapper performMapping:&error];
    
    return infoMapped;
    }
    

    These posts led me to the solution I have suggested:

    I hope it helps. I guess some other will give better solutions when the final version will be released (with better documentation too...).