RestKit 从本地存储的 XML 解析/对象映射
Posted
技术标签:
【中文标题】RestKit 从本地存储的 XML 解析/对象映射【英文标题】:RestKit parsing/Object mapping from locally stored XML 【发布时间】:2013-11-28 00:42:51 【问题描述】:我正在下载一个 zip,解压缩它,然后尝试从 zip 中包含的 xml 文件解析和对象映射数据。我知道如果 XML 文件不在 zip 中,我可以执行类似的操作
NSURL *URL = [NSURL URLWithString:@"http://restkit.org/articles"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
RKObjectRequestOperation *objectRequestOperation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[ responseDescriptor ]];
但是因为我要下载一个 zip,我必须(或者至少我认为我必须)使用以下代码
NSURL *URL = [NSURL URLWithString:@"http://www.mediafire.com/download/6tfd33xkiepx8a3/db_UI.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
self.operation = [[AFHTTPRequestOperation alloc]
initWithRequest:request];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"testDownload"];
self.operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
// Set download completion block
[self.operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
NSLog(@"Successfully downloaded file to %@", path);
NSString *zipPath = path;
NSString *destinationPath = [paths objectAtIndex:0];
[SSZipArchive unzipFileAtPath:zipPath toDestination:destinationPath delegate:self];
failure:^(AFHTTPRequestOperation *operation, NSError *error)
// NSLog(@"error: %@", operation.responseString);
];
// Start download operation
[self.operation start];
[RKMIMETypeSerialization registerClass:[RKXMLReaderSerialization class] forMIMEType:@"application/xml"];
那么在这种情况下,我该如何使用RKObjectMapping
。还是有其他选择?........
【问题讨论】:
我知道我不应该在 setCompletionBlockWithSuccess 的 unzipFileAtPath 调用中将 self 设置为委托。我会尝试解决这个问题 【参考方案1】:这是来自 Rest-Kit 文档,如果您可以更改 MIME 类型,则此解析 JSON 对象,您可以对 XML 执行任何操作
你可以在这里找到它:Rest-Kit docs
NSString* JSONString = @" \"name\": \"The name\", \"number\": 12345";
NSString* MIMEType = @"application/json";
NSError* error = nil;
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:MIMEType];
id parsedData = [parser objectFromString:JSONString error:&error];
if (parsedData == nil && error)
// Parser error...
RKObjectMappingProvider* mappingProvider = [RKObjectManager sharedManager].mappingProvider;
RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:parsedData mappingProvider:mappingProvider];
RKObjectMappingResult* result = [mapper performMapping];
if (result)
// Yay! Mapping finished successfully
【讨论】:
这行得通!如果我想映射到核心数据对象,这将如何改变?以上是关于RestKit 从本地存储的 XML 解析/对象映射的主要内容,如果未能解决你的问题,请参考以下文章
iOS7 是不是有轻量级 JSON 到对象映射器(不是 RestKit 或 NSJSONSerialization)?
解析映射器 XML 时出错。原因:java.lang.NullPointerException
使用 RestKit 0.2 从 CoreData 获取本地数据