2012-02-26 34 views
2

我想在mac應用程序中用戶NSJSONSerialization,但我不能得到它的工作,我試圖讓它加載UserTimeline,並只顯示最後一條推文的文本,多數民衆贊成它,但我似乎無法找到正確的方式來使用它。該API我曾嘗試使用:使用NSJSONSerialization的mac

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上工作。

關於如何使用mac的NSJSONSerialization的任何鏈接都很棒,或者任何可能的幫助也是一個主要的感謝。我試圖在蘋果開發者論壇上獲得幫助,但沒有運氣。

回答

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 
} 
+0

順便說一句,通過類做才能讓你與你的服務器通信 – 2012-02-26 14:47:13

+0

感謝這個工作就像一個魅力! – 2012-02-26 15:11:47

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);   
}