2013-01-23 52 views
0

我得到的JSON對象從https://twitter.com/statuses/public_timeline.json使用NSJSONSerialization

所以顯示的數據,我的代碼是下一個:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    NSURL *url = [NSURL URLWithString:@"https://twitter.com/statuses/public_timeline.json"]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    [[NSURLConnection alloc] initWithRequest:request delegate:self]; 


} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    students = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
    for(NSDictionary *item in students) { 
     NSLog(@"Message: %@", [item objectForKey:@"message"]); 
    } 
} 

所以,我得到了一個錯誤:

2013-01-23 21:42:02.672 students[94907:11603] -[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x7471580 
2013-01-23 21:42:02.681 students[94907:11603] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x7471580' 

回答

0

JSON正在創建* item作爲NSString。也許它已經是你想要的消息了

+0

是的,我有嘗試過,我可以看到「錯誤」,但是我想要顯示每個字段作爲e的消息xample。 – grouser

0

這意味着你正在調用objectForKey:從一個nil對象中取出,而不是NSLog(... [item objectForKey:@「message」],試着用NSLog(@"%@", item);來看看它是什麼。你應該嘗試以下,將數據下載到一個字符串,然後傳遞串入NSJSONSerializer的迭代

NSMutableString *responseData = [[NSMutableString alloc] init]; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    NSURL *url = [NSURL URLWithString:@"https://twitter.com/statuses/public_timeline.json"]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    [[NSURLConnection alloc] initWithRequest:request delegate:self]; 


} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
     NSLog(@"we got a response "); 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ 
     NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
     [responseData appendString:response]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSDictionary *students = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:[responseData UTF8String] 
                        length:[responseData lengthOfBytesUsingEncoding:NSUTF8StringEncoding]] 
                  options:0 
                   error:nil]; 
    for(NSDictionary *item in students) { 
     NSLog(@"Message: %@", [item objectForKey:@"message"]); 
    } 
} 
0

嘗試此我希望這將幫助你..

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 

    mData = [[NSMutableData alloc] init]; 
    [mData appendData:data]; 
} 



-(void)connectionDidFinishLoading:(NSURLConnection *)connection { 

     NSDictionary *students = [NSJSONSerialization JSONObjectWithData: mData options:kNilOptions error:nil]; 

    for(NSDictionary *item in students) { 
      NSLog(@"Message: %@", item); 
     } 
    NSLog(@"NSDictionary: %@", students); 
}