我正在尝试阅读以下json:
[{"result":"1","msg":"Login Successful.”,”title":"Login","redirect":"index.php","servers":"{\"140\":\"10 minute Email\"}","server”:”xxx.xxx.xxx.xxx”}]
像这样:
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"Response ==> %@", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSLog(@"%@",jsonData);
NSInteger success = [(NSNumber *) [jsonData objectForKey:@"result"] integerValue];
NSLog(@"%d",success);
if(success == 1)
{
NSLog(@"Login SUCCESS");
[self alertStatus:@"Logged in Successfully." :@"Login Success!"];
} else {
NSString *error_msg = (NSString *) [jsonData objectForKey:@"error_message"];
[self alertStatus:error_msg :@"Login Failed!"];
}
但是我收到以下错误:
2014-01-01 20:44:08.857 Server Monitor [9704:70b] - [__ NSArrayM objectForKey:]:无法识别的选择器发送到实例0x8e59950
2014-01-01 20:44:08.857 Server Monitor [9704:70b]异常: - [__ NSArrayM objectForKey:]:无法识别的选择器发送到实例0x8e59950
我认为问题是json是一个数组,我该如何处理呢?
答案 0 :(得分:1)
问题是你的JSON的根对象是一个数组:
[ … ]
但你错误地认为它是字典:
NSDictionary *jsonData = (NSDictionary *)[jsonParser objectWithString:responseData error:nil];
如果响应始终是包含一个对象的数组,则可以执行类似的操作:
NSArray *jsonArray = (NSArray *)[jsonParser objectWithString:responseData error:nil];
NSDictionary *jsonData = [jsonArray lastObject];
但更安全的方法是检查班级:
NSObject *object = [jsonParser objectWithString:responseData error:nil];
if ([object isKindOfClass:[NSArray class]]) {
// it's an array …
} else if ([object isKindOfClass:[NSDictionary class]]) {
// it's a dictionary …
}
最后,
nil
传递给错误参数;你应该添加错误处理。答案 1 :(得分:0)
像这样使用
NSString *theJSON = [request responseString];
// Now we have successfully captured the JSON ouptut of our request.
// Alloc and initialize our JSON parser.
SBJsonParser *parser = [[SBJsonParser alloc] init];
// Actually parsing the JSON.
NSMutableDictionary *jsonDictionary = [parser objectWithString:theJSON error:nil];
快乐编码