2012-05-06 27 views
0

即時通訊使用SBJSON解析我的迴應,總線以某種方式我不能得到我的數據。 我應該如何解析這個reponed?在我的Objective-C程序中解析json響應

{"StatusCode":0,"Message":"email already exists","Content":{"HasApplication":false,"IsFaceBook":false,"UserActive":false,"UserAuthenticationType":0,"UserCredits":0,"UserDayAdded":0,"UserEmail":null,"UserEmailWasVerified":false,"UserGuid":null,"UserID":0,"UserSellerApproved":false,"UserTokef":0},"TotalCount":0} 

我開始是這樣的:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    [responseData setLength:0]; 
    NSLog(@"%@",response); 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    [responseData appendData:data]; 
    NSLog(@"Data recived");  
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    NSLog(@"Connection failed! Error - %@ %@",[error localizedDescription], 
      [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); 
    responseData = nil; 

} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSLog(@"conenction loading finished"); 

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
    SBJsonParser *parser = [[SBJsonParser alloc] init]; 
    NSMutableDictionary *jsonDictionary = [parser objectWithString:responseString error:nil]; 
} 

但下一步該做什麼我需要的StatusCode值和用戶名。你有

+0

打印jsonDictionary,看到它你自己,你會如何檢索在字典鍵的值/對象? – 0x8badf00d

回答

0

一個字典,你可以使用它,例如:

NSMutableDictionary *jsonDictionary = [parser objectWithString:responseString error:nil]; 
NSNumber * statusCode = [jsonDictionary objectForKey:@"StatusCode"]; 
NSString * message = [jsonDictionary objectForKey:@"Message"]; 
NSDictionary * content = [jsonDictionary objectForKey:@"Content"]; 
// etc... 
0

從JSON字符串的長相,你有一個字典有三個鍵值對,它們是另一個辭典之一幾個關鍵值對。所以對付,一旦你分配了JSON responseString到您的NSMutableDictionary:

應該是這樣的:

NSNumber *statusCode = [jsonDictionary objectForKey:@"StatusCode"]; 
NSDictionary *contentDict = [jsonDictionary [email protected]"Content"]; 
NSString *userID = [contentDict [email protected]"UserID"]; 

在一個完全不同的說明,如果你打算做了很多基於web的服務交互,您可能需要認真對待AFNetworking。它會改變你的生活:)

另外,我看不出爲什麼你需要jsonDictionary是一個NSMutableDictionary。除非您稍後更改它,否則使用NSDictionary,它的開銷較小。

0

well ..... NSMutableDictionary *jsonDictionary = [parser objectWithString:responseString 也許這不是NSMutableDictionary,而是NSDictionary。 然後:

NSString *statusCode = [jsonDictionary valueForKey:@"StatusCode"]; 
NSDictionary *contentDict = [jsonDictionary [email protected]"Content"]; 
NSString *userID = [contentDict [email protected]"UserID"];