How to get values from a dictionary in iOS

孤者浪人 提交于 2019-12-05 00:37:00
cream-corn

Using modern Objective-C, accessing things in arrays and dictionaries become easier.

You should use the following syntax:

id<NSObject> value = dictionary[@"key"];

Similarly,

id<NSObject> value = array[1]; // 1 is the index

Applying the above to the question:

NSString *error = json[@"error"];

NSDictionary *value = json[@"value"];

BOOL user = [json[@"value"][@"user"] boolValue];

As in the above line, nesting is allowed, but it is not a good practice.

NSNumber *error = [json objectForKey:@"error"];
if ([error intValue] == 0)
{
    NSLog(@"login successful");

    NSDictionary *value = [json objectForKey:@"value"];
    NSNumber *user = [value objectForKey:@"user"];
    if ([user boolValue])
    {
        NSLog(@"user == true");
    }
    else
    {
        NSLog(@"user == false");
    }
}
else
{
    NSLog(@"login failed");
}
SARATH SASI

The dictionaries that normally returning from the server will be as a key value pair. if you are looking for accessing these values that corresponds to a key, then these code may help you

NSString *varname = [[NSString alloc]initWithFormat:@"%@",[dictionaryname objectForKey:@"key"]];

For get error value from your JSON Dictionary.

NSString *error = [myJSONDicName objectForKey:@"error"];

For get user value from your JSON Dictionary.

NSString *error = [[myJSONDicName objectForKey:@"value"] objectForKey:@"user"];

EDITED:

You just need to change In your

if ([error isEqualToString:@"o"])
                            _^_
                             |

change 'o' to '0'

You can use the below code

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
   {
          NSString *respstring = [[NSString alloc]initWithData:loginJsonData encoding:NSUTF8StringEncoding];
          NSDictionary *dic = [responseString JSONValue];
         NSLog(@"%@",dic);
         NSNumber *error = [dic objectForKey:@"error"];
        if([error intValue] == 0)  {
           NSLog(@"login successful");
        }
        else
        {
            NSLog(@"login fail");
        }

        NSString *user = [value objectForKey:@"user"];
        BOOL userStatus = [user boolValue];
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!