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

前端 未结 9 1184
悲&欢浪女
悲&欢浪女 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:01

    This works for Restkit 0.21.0:

    NSString* jsonFilePath = [[NSBundle mainBundle] pathForResource:@"fileName"
                                                     ofType:@"json"];
    
    NSString* JSONString = [NSString stringWithContentsOfFile:jsonFilePath
                                                  encoding:NSUTF8StringEncoding
                                                     error:NULL];
    
    
    NSError* error;
    NSData *data = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    id parsedData = [RKMIMETypeSerialization objectFromData:data MIMEType:RKMIMETypeJSON error:&error];
    if (parsedData == nil && error) {
        // Parser error...
    }
    
    //_objectManager is RKObjectManager instance
    NSMutableDictionary *mappingsDictionary = [[NSMutableDictionary alloc] init];
    for (RKResponseDescriptor *descriptor in _objectManager.responseDescriptors) {
        [mappingsDictionary setObject:descriptor.mapping forKey:descriptor.keyPath];
    }
    
    RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithRepresentation:parsedData mappingsDictionary:mappingsDictionary];
    NSError *mappingError = nil;
    BOOL isMapped = [mapper execute:&mappingError];
    if (isMapped && !mappingError) {
        NSLog(@"result %@",[mapper mappingResult]);
    }
    

提交回复
热议问题