[英]Error getting JSON and trying to parse it [iOS]
我整天都在看這本書,在看其他解決方案,但是什么也沒有,我無法解決我的問題。
我想獲取https://alpha-api.app.net/stream/0/posts/stream/global的JSON,對其進行解析,以便提取用戶名以及將來的其他屬性,如post,avatar ...這是我的viewDidLoad
,在其中建立了與URL的連接,然后將其更改為NSData對象。
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:@"https://alpha-api.app.net/stream/0/posts/stream/global"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSError *jsonParsingError = nil;
NSArray *timeline= [NSJSONSerialization JSONObjectWithData:response
options:0 error:&jsonParsingError];
NSDictionary *user;
for(int i=0; i<[timeline count];i++)
{
user = [timeline objectAtIndex:i];
NSLog(@"Statuses: %@", [user objectForKey:@"username"]);
}
我的程序開始運行,然后停止。 我知道何時停止(user = [timeline objectiAtIndex:i])
但我不知道為什么...另一個問題: [user objectForKey:@"username"]
是否足以提取用戶名?
由於以下行返回了NSDictionary,而不是NSArray,因此出現錯誤。
NSArray* timeline= [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
應該是這樣
NSDictionary* timeline= [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
並且您的邏輯也應作相應調整。
Web服務很可能返回的是JSON字典,而不是數組。 這將導致無法識別的選擇器異常引發[timeline objectAtIndex:i]
。 打印出請求在調試器中返回的內容,如果它是字典,則需要在迭代之前找到如何訪問所需的數組。
當您正在檢索的數據結構表明它實際上將是NSDictionary時,您的解析邏輯錯誤地認為時間軸將是NSArray。
時間軸數據包含在字典中,可以通過鍵“數據”訪問該字典。 我會按照以下方式做一些事情:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:@"https://alpha-api.app.net/stream/0/posts/stream/global"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSError *jsonParsingError = nil;
NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
NSArray *timelineArray;
if (responseObject) {
timelineArray = [responseObject objectForKey:@"data"];
NSDictionary *user; // user data
for (NSDictionary *status in timelineArray) {
user = [status objectForKey:@"user"];
NSLog(@"Status: %@", [status objectForKey:@"text"]);
NSLog(@"Status by user: %@\n\n", [user objectForKey:@"username"]);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.