Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get values from a dictionary in iOS

I am new to iOS. I created a login page and everything works fine. I used JSON for checking username and password and got the response from server in a dictionary format. I want to extract the values from the dictionary and check them in my program. The response which I get from the server is:

json: {
        error = 0;
        msg = "";
        value = {
                  user = false;
                };
      };

First I want to check if the value with the key error is 0 or 1. Then I want to check the value with the key user. I don't know how I should code to check it. Can anyone help?

The code which I tried is below:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *respString = [[NSString alloc] initWithData:loginJSONData encoding:NSUTF8StringEncoding];

    SBJsonParser *objSBJSONParser = [[SBJsonParser alloc] init];

    NSDictionary *json = [[NSDictionary alloc] initWithDictionary:[objSBJsonParser objectWithString:respString]];

    NSLog(@"json: %@",json);

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

    NSLog(@"error: %@", error);

    if ([error isEqualToString:@"o"])
    {
        NSLog(@"login successful");
    }
    else
    {
        NSLog(@"login fail");
    }
}
like image 907
Saba Sayed Avatar asked Nov 14 '13 05:11

Saba Sayed


People also ask

How can I get values from dictionary without key?

Use dict.get() to get the default value for non-existent keys. You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist.

What is dictionary in IOS Swift?

A dictionary is a type of hash table, providing fast access to the entries it contains. Each entry in the table is identified using its key, which is a hashable type such as a string or number. You use that key to retrieve the corresponding value, which can be any object.


2 Answers

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.

like image 125
cream-corn Avatar answered Oct 18 '22 20:10

cream-corn


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");
}
like image 5
Inder Kumar Rathore Avatar answered Oct 18 '22 21:10

Inder Kumar Rathore