【问题标题】:NSURLconnection and jsonNSURL 连接和 json
【发布时间】:2026-01-31 06:10:01
【问题描述】:

我知道这是一个愚蠢的问题,但我不知道该怎么做。从此链接the requested link 可以使用 NSURLconnection 返回 json 数据吗?我希望有人检查此链接并告诉我这是否可能,因为我是这方面的新手。

编辑:

我尝试了 NSJSONSerialization

- (void)viewDidLoad
{
    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.goalzz.com/main.aspx?region=-1&area=6&update=true"]];
    connectionData = [[NSURLConnection alloc]initWithRequest:req delegate:self];
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
 }
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    Data = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [Data appendData:data];
}

 - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *jsonParsingError = nil;
id object = [NSJSONSerialization JSONObjectWithData:Data options:0 error:&jsonParsingError];

if (jsonParsingError) {
    NSLog(@"JSON ERROR: %@", [jsonParsingError localizedDescription]);
} else {
    NSLog(@"OBJECT: %@", [object class]);
}
}

我在控制台中收到此错误消息:

JSON 错误: 操作无法完成。 (可可错误 3840。)

【问题讨论】:

  • 首先,该 URL 不返回 JSON。其次,NSURLConnection 不提供内置的 JSON 解析器,因此您必须为此使用第三方库。 TouchJSON 是一种选择。
  • 谢谢@Anton Holmquist.so 使用 ToushJSON 我可以检索数据并解析它吗?
  • 没有。考虑获取数据并将其解析为两个单独的任务。首先使用 NSURLConnection 或任何其他请求库获取它,然后使用 TouchJSON 或任何其他解析库对其进行解析。

标签: iphone objective-c ios xcode nsurlconnection


【解决方案1】:

正如上面的评论所暗示的,该链接不会返回 JSON。但是,假设您确实有这样的链接,您可以使用 NSJSONSerialization 类将 JSON 数据解析为 Objective-C 类:

http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40010946

把它和 NSURLConnection 结合起来,你就可以做你想做的事了。下面是实现 NSURLConnection 的演练:

http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-BAJEAIEE

这里是您需要的大纲。显然这不是工作代码:

- (void)downloadJSONFromURL {
    NSURLRequest *request = ....
    NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    // ...
}

NSMutableData *urlData;

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    urlData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [urlData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSError *jsonParsingError = nil;
    id object = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&jsonParsingError];

    if (jsonParsingError) {
        DLog(@"JSON ERROR: %@", [jsonParsingError localizedDescription]);
    } else {
        DLog(@"OBJECT: %@", [object class]);
    }
}

【讨论】: