0

我使用 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。

4

3 回答 3

0

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

NSMutableDictionary *jsonDictionary = [parser objectWithString:responseString error:nil];
NSNumber * statusCode = [jsonDictionary objectForKey:@"StatusCode"];
NSString * message = [jsonDictionary objectForKey:@"Message"];
NSDictionary * content = [jsonDictionary objectForKey:@"Content"];
// etc...
于 2012-05-07T00:00:57.543 回答
0

从 JSON 字符串的外观来看,您有一个包含三个键值对的字典,其中一个是另一个具有多个键值对的字典。因此,一旦你将 JSON responseString 分配给你的 NSMutableDictionary,就可以处理这个问题:

应该是这样的:

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

完全不同的是,如果您要进行大量的 Web 服务交互,您可能需要认真研究 AFNetworking。它会改变你的生活 :)

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

于 2012-05-07T00:01:59.197 回答
0

好吧..... NSMutableDictionary *jsonDictionary = [parser objectWithString:responseString 也许不是 NSMutableDictionary,而是 NSDictionary。进而:

NSString *statusCode = [jsonDictionary valueForKey:@"StatusCode"];
NSDictionary *contentDict = [jsonDictionary objectForKey@"Content"];
NSString *userID = [contentDict valueForKey@"UserID"];
于 2012-05-07T00:18:00.113 回答