简体   繁体   中英

Parse Json with dynamic response objective-c

I'm having some trouble parsing the following error response to display in an 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"
}
},

Usually I'd do something like this to get the objects inside of each dictionary but the problem is the keys will change depending on the error. How do I properly parse through this?

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

This will just print email, password, name and surname. I can do something like this but I won't always know what the second key is. In this case it's "password" -

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

Got it working with the following code -

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];

You should not iterate over NSDictionnary. You should try something like :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM