NSURLconnection和json

问题描述 投票:1回答:1

我知道这是一个愚蠢的问题,但我知道如何做到这一点。从这个链接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.)

iphone objective-c ios xcode nsurlconnection
1个回答
10
投票

如上面的评论所示,该链接不会返回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]);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.