2012-07-03 57 views
1

我知道這是一個愚蠢的問題,但我很瞭解如何做到這一點。從這個鏈接the requested link是可能返回json數據與NSURLconnection?我希望有人檢查這個鏈接,並告訴我是否可能,因爲我是這個新東西。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.)

+0

首先,該URL不返回JSON。其次,NSURLConnection不提供內置的JSON解析器,因此您必須爲此使用第三方庫。 [TouchJSON](https://github.com/TouchCode/TouchJSON)是一種選擇。 –

+0

謝謝@Anton Holmquist.so與ToushJSON我可以檢索數據解析嗎? – adellam

+0

不需要。想想獲取數據並將其解析爲兩個單獨的任務。首先使用NSURLConnection或任何其他請求庫來獲取它,然後使用TouchJSON或任何其他解析庫來解析它。 –

回答

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]); 
    } 
} 
+0

謝謝@Chris H我會試試這個。 – adellam