我有一个包含json文件的链接。我的意思是,如果我在Chrome中启动该链接,则会在我的计算机上下载一个扩展名为.json的文件。说的链接是www.foffa.com/sampleList.json
我是AFNetworking的新手,不知道如何解析此json,而不必将这个文件写到磁盘上。
我的代码如下所示,我很确定必须为此使用流和所有方法,但是我不确定如何使用。到现在"Request failed: unacceptable content-type: text/plain"
为止,我得到一个错误,我猜它期望内容类型为"Content-Type" = "application/octet-stream";
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFHTTPResponseSerializer serializer];
operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/octet-stream"];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Data retrived");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alertView show];
}];
更改第二行:
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFHTTPResponseSerializer serializer];
对此:
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
请注意,您正在使用AFJSONResponseSerializer
序列化的响应。
更新
从以下注释中的信息更新我的答案,看来您实际上是要从服务器下载JSON文件,然后解析该文件,而不是直接从HTTP响应中解析JSON:
为此,将内容类型更改为text/plain
或与下载的file/data
解析一起作为String
或JSON
对象,如下所示:
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:nil];
operation.responseSerializer = [AFHTTPResponseSerializer serializer];
operation.responseSerializer.acceptableContentTypes =
[NSSet setWithObjects:@"application/octet-stream", @"text/plain", nil];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error;
id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&error];
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"JSON: %@", json);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alertView show];
}];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句