Parse Json具有动态响应目标-c

时间:2014-03-18 17:01:38

标签: ios iphone json

我在解析以下错误响应时遇到问题,无法在UIAlertView中显示 -

{"error": {
"email": {
  "isEmpty": "Value is required and can't be empty"
},
"password": {
  "isEmpty": "Value is required and can't be empty"
},
"name": {
  "isEmpty": "Value is required and can't be empty"
},
"surname": {
  "isEmpty": "Value is required and can't be empty"
}
},

通常我会做这样的事情来获取每个字典中的对象,但问题是密钥会根据错误而改变。我如何正确地解析这个?

NSDictionary * Json = [NSJSONSerialization JSONObjectWithData:data
                                                                  options:kNilOptions
                                                                  error:&error];
NSDictionary * error = [Json objectForKey:@"error"];
for (NSDictionary * subError in error) {
                 NSLog(@"subError = %@", subError);
             }

这将只打印电子邮件,密码,姓名和姓氏。我可以做这样的事情,但我不知道第二把钥匙是什么。在这种情况下,密码"密码" -

NSDictionary * error = [[Json objectForKey:@"error"] objectForKey:@"password"];

2 个答案:

答案 0 :(得分:0)

使用以下代码 -

NSDictionary * subError = [[luckyNumbers objectForKey:@"error"] objectForKey:[[error allKeys] objectAtIndex:0]];
title = [[error allKeys] objectAtIndex:0];
message = [[[luckyNumbers objectForKey:@"error"] objectForKey:[[error allKeys] objectAtIndex:0]] objectForKey:[[subError allKeys] objectAtIndex:0]];

UIAlertView *alert = [[UIAlertView alloc]
                                           initWithTitle:title
                                           message:message
                                           delegate:nil
                                           cancelButtonTitle:@"OK"
                                           otherButtonTitles:nil];
                     [alert show];

答案 1 :(得分:-1)

您不应该遍历NSDictionary。你应该尝试类似的东西:

NSDictionary * error = [Json objectForKey:@"error"];
for (NSString * subErrorKey in [error allKeys]) {
    NSLog(@"subError = %@", [[error objectForKey:subErrorKey] objectForKey:isEmpty]);
}