Deserializing local NSString of JSON into objects via RestKit (no network download)

前端 未结 9 1153
悲&欢浪女
悲&欢浪女 2020-12-14 20:49

Is it possible to deserialize an NSString of JSON into objects via RestKit? I checked the API list here and could not find something that would serve for this p

9条回答
  •  粉色の甜心
    2020-12-14 21:14

    This works for Restkit 0.20, using Core Data Entities. It is based in the solution given by @innerself

    NSString* jsonFilePath = [[NSBundle mainBundle] pathForResource:@"info-base"
                                                             ofType:@"json"];
    
    NSString* JSONString = [NSString stringWithContentsOfFile:jsonFilePath
                                                     encoding:NSUTF8StringEncoding
                                                        error:NULL];
    
    
    NSError *error = nil;
    
    NSData *data = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    id parsedData = [RKMIMETypeSerialization objectFromData:data MIMEType:RKMIMETypeJSON error:&error];
    if (parsedData == nil && error) {
        // Parser error...
        NSLog(@"parse error");
    }
    
    //_objectManager is RKObjectManager instance
    NSMutableDictionary *mappingsDictionary = [[NSMutableDictionary alloc] init];
    for (RKResponseDescriptor *descriptor in [RKObjectManager sharedManager].responseDescriptors) {
    
        [mappingsDictionary setObject:descriptor.mapping forKey:descriptor.keyPath];
    }
    
    RKManagedObjectMappingOperationDataSource *datasource = [[RKManagedObjectMappingOperationDataSource alloc]
                                                             initWithManagedObjectContext:[RKManagedObjectStore defaultStore].persistentStoreManagedObjectContext
                                                                                    cache:[RKManagedObjectStore defaultStore].managedObjectCache];
    
    RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithRepresentation:parsedData
                                                               mappingsDictionary:mappingsDictionary];
    [mapper setMappingOperationDataSource:datasource];
    
    NSError *mappingError = nil;
    BOOL isMapped = [mapper execute:&mappingError];
    if (isMapped && !mappingError) {
        // data is in [mapper mappingResult]
    }
    

提交回复
热议问题