我从https://twitter.com/statuses/public_timeline.json
获取JSON对象所以,我的代码是下一个:
- (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 :(得分:0)
JSON正在创建*项作为NSString。而不是NSLog(... [item objectForKey:@“message”],请尝试NSLog(@"%@", item);
查看它是什么。也许它已经是您想要的消息
答案 1 :(得分:0)
这意味着你正在调用objectForKey:在一个nil对象之外,你应该尝试以下方法将数据下载到字符串中,然后将该字符串传递给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"]);
}
}
答案 2 :(得分: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);
}