在我的objective-c程序中解析json响应

时间:2012-05-06 23:54:12

标签: iphone objective-c json sbjson

我使用SBJSON来解析我的回复,总线不知何故我无法获取我的数据。 我该如何解析这个被推迟的?

{"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值和UserID。

3 个答案:

答案 0 :(得分:0)

你有一本词典,你可以使用它,例如:

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

答案 1 :(得分:0)

从JSON字符串的外观来看,您有一个包含三个键值对的词典,其中一个是具有多个键值对的另一个词典。因此,一旦将JSON responseString分配给NSMutableDictionary:

,就要处理它

应该是这样的:

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

完全不同的是,如果您要进行大量的网络服务互动,您可能需要认真审视AFNetworking。它会改变你的生活:)

另外,我不明白为什么你需要jsonDictionary作为NSMutableDictionary。除非您稍后更改它,否则使用NSDictionary,它的开销更小。

答案 2 :(得分:0)

以及..... NSMutableDictionary *jsonDictionary = [parser objectWithString:responseString 也许它不是NSMutableDictionary,而是NSDictionary。 然后:

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