RestKit - 将数据库与本地 JSON 文件同步

Posted

技术标签:

【中文标题】RestKit - 将数据库与本地 JSON 文件同步【英文标题】:RestKit - Sync Data Base with local JSON file 【发布时间】:2014-10-24 21:55:32 【问题描述】:

我提供了一个示例 JSON 文件(出于测试目的,我没有提前访问 Web 服务)。加载文件并转换为NSDictionary 后,如何使用该字典并同步我的数据库?我读过的所有教程和示例都使用 Web 服务

我已经为所有对象创建了映射并应用了它们的关系。

一个例子:

+ (RKEntityMapping *) mapTableInManagedObjectStore:(RKManagedObjectStore *)managedObjectStore

    RKEntityMapping *tableMapping = [RKEntityMapping mappingForEntityForName:@"Table" inManagedObjectStore:managedObjectStore];
    tableMapping.identificationAttributes = @[@"tableID"];
    [tableMapping addAttributeMappingsFromDictionary:@
                                                       @"ID":@"tableID",
                                                       @"TableNumber":@"tableNumber",
                                                       @"NumberOfChairs":@"numberOfChairs"];

    return tableMapping;

【问题讨论】:

您是否尝试使用文件 URL?它曾经可以工作,但我似乎记得有什么东西把它弄坏了。否则,只需将文件托管在某处,然后更改您稍后用来访问它的 URL。 【参考方案1】:

以下是我的做法和效果:

 // read file
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:contentPath encoding:NSUTF8StringEncoding error:NULL];

NSString* MIMEType = @"application/json";
NSError* parseError;

NSData *data = [myJSON dataUsingEncoding:NSUTF8StringEncoding];
id parsedData = [RKMIMETypeSerialization objectFromData:data MIMEType:MIMEType error:&parseError];
if (parsedData == nil && parseError) 
    NSLog(@"Cannot parse data: %@", parseError);


//convert NSData to NSDictionary
NSError *errorJson=nil;
NSDictionary* responseDict = [NSJSONSerialization JSONObjectWithData:lookServerResponseData options:kNilOptions error:&errorJson];
 NSDictionary *tableDic = responseDict;

//perform mapping
    RKManagedObjectStore *managedObjectStore = [HAObjectManager sharedManager].managedObjectStore;
    Table *table = [[Table findAll] firstObject];
    RKManagedObjectMappingOperationDataSource *mappingDataSource = [[RKManagedObjectMappingOperationDataSource alloc] initWithManagedObjectContext:managedObjectStore.mainQueueManagedObjectContext cache:managedObjectStore.managedObjectCache];

    RKMappingOperation  *mappingOperation = [[RKMappingOperation alloc] initWithSourceObject:tableDic destinationObject:table mapping:[MappingProvider mapTablebjectStore:managedObjectStore]];

    mappingOperation.dataSource = mappingDataSource;
    NSError *error = nil;
    [mappingOperation performMapping:&error];

RKMappingOperation 的工作是将值从源对象映射到目标对象。 现在表属性用 tableDic 值更新。 (表格有点像NSManagedObject

【讨论】:

以上是关于RestKit - 将数据库与本地 JSON 文件同步的主要内容,如果未能解决你的问题,请参考以下文章

RestKit 无法将 JSON 请求中格式为字符串的日期保存到我的本地数据库

通过 RestKit 将 JSON 的本地 NSString 反序列化为对象(无网络下载)

如何使用带有 RKObjectMapping 的 RestKit 0.24 将本地 JSON 字符串映射到对象?

Restkit 将对象加载到现有对象

RestKit 0.20.1 映射本地 JSON “此类不符合键值编码...”

将 RestKit 与本地服务器一起使用