2

我正在尝试NSJSONSerialization在 Mac 应用程序中使用,但我无法让它工作,我试图让它加载 UserTimeline,并只显示最后一条推文的文本,仅此而已,但我不能似乎找到了使用它的正确方法。我尝试使用的api:

http://api.twitter.com/1/statuses/user_timeline.json?screen_name=AlexTrott_

http://twitter.com/statuses/user_timeline/AlexTrott_.json

但是我都没有看过,这就是我一直在尝试使用的方式NSJSONSerialization

NSString *tweets = [NSURL URLWithString:@"http://twitter.com/statuses/user_timeline/AlexTrott_.json"];
    NSData *jsonData = [tweets dataUsingEncoding:NSUTF8StringEncoding];
    NSError *e = nil;
    NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&e];
    NSLog(@"%@", json);

这正是我一直用来查看它是否已加载它们的方法,但它一直让我失望。

我也尝试过尝试这种方法http://www.raywenderlich.com/5492/working-with-json-in-ios-5但是那仅适用于iOS,我不知道我会如何得到它在 Mac 上工作。

任何关于如何使用NSJSONSerializationmac 的链接都会很棒,或者任何帮助也可能是非常感谢的。我尝试在苹果开发者论坛上获得帮助,但没有运气。

4

2 回答 2

2
NSURL *tweets = [NSURL URLWithString:@"http://twitter.com/statuses/user_timeline/AlexTrott_.json"];
    //NSData *jsonData = [tweets dataUsingEncoding:NSUTF8StringEncoding];
     //NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&e];
NSData *jsonData=[NSData dataWithContentsOfURL:tweets];
NSError *e = nil;

   id yourJsonData=[NSJSONSerialization JSONObjectWithData:jsonData options:
               NSJSONReadingMutableContainers error:&error];
NSLog("%@",yourJsonData );//you must get a json object here

//let's assume you need to get the key kalled user_name from your JSON Response

NSDictionary *theJson=[yourJsonData objectForKey:@"user_name"];

for(NSMutableArray *usernames in theJson){

// do something with usernames from your object
}
于 2012-02-26T14:46:13.563 回答
0

我的申请还收到了他的最后一条推文。您应该考虑这些请求对服务器的限制(每小时 350 个)。如果超过这个限制,nsdata中没有nsarray就是nsdictionary,描述了错误和请求,这无疑会被考虑进去。我是这样做的:

NSError* error = nil;

id responseBody = [NSJSONSerialization JSONObjectWithData:data 
                                                  options:NSJSONReadingMutableContainers
                                                    error:&error];

if (error) {

    [[NSAlert alertWithError:error] runModal];
} 

if ([responseBody respondsToSelector:@selector(objectAtIndex:)]) {

    else { 

        if ([responseBody count]) {

            NSString* currentStatus = [[responseBody objectAtIndex:0] objectForKey:@"text"]; //now you can do smth with your status))
        } 
        else {

            NSLog(@"You have not tweetted yet!");
        }
    } 
} 
else if([responseBody respondsToSelector:@selector(objectForKey:)]) {

    NSString* error = [responseBody objectForKey:@"error"];
    NSLog(@"CURRENT STATUS ERROR => %@", error);        
}
于 2012-03-29T10:10:28.117 回答