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

前端 未结 9 1176
悲&欢浪女
悲&欢浪女 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条回答
  •  旧时难觅i
    2020-12-14 21:21

    You can see how RestKit does this internally in the RKManagedObjectResponseMapperOperation class.

    There are three stages of this operation.

    The first is to parse the JSON string into NSDictionarys, NSArrays, etc. This is the easiest part.

    id parsedData = [RKMIMETypeSerialization objectFromData:data
                                                   MIMEType:RKMIMETypeJSON
                                                      error:error];
    

    Next you need to run a mapping operation to convert this data into your NSManagedObjects. This is a bit more involved.

    __block NSError *blockError = nil;
    __block RKMappingResult *mappingResult = nil;
    NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
    operationQueue.maxConcurrentOperationCount = 1;
    
    [[RKObjectManager sharedManager].managedObjectStore.persistentStoreManagedObjectContext performBlockAndWait:^{
    

    Remember to replace this dictionary with your own mappings. The key [NSNull null] maps this object from the root.

        NSDictionary *mappings = @{[NSNull null]: [jotOfflineRequestStatus mapping]};
    
        RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithRepresentation:parsedData
                                                                   mappingsDictionary:mappings];
    
        RKManagedObjectMappingOperationDataSource *dataSource = [[RKManagedObjectMappingOperationDataSource alloc]
                                                                 initWithManagedObjectContext:[RKManagedObjectStore defaultStore].persistentStoreManagedObjectContext
                                                                 cache:[RKManagedObjectStore defaultStore].managedObjectCache];
        dataSource.operationQueue = operationQueue;
        dataSource.parentOperation = mapper;
        mapper.mappingOperationDataSource = dataSource;
    
        [mapper start];
        blockError = mapper.error;
        mappingResult = mapper.mappingResult;
    }];
    

    You now need to run the tasks that have been put into the operationQueue we created. It is at this stage that connections to existing NSManagedObjects are made.

    if ([operationQueue operationCount]) {
        [operationQueue waitUntilAllOperationsAreFinished];
    }
    

提交回复
热议问题