0

I have the following JSON data trying to parse in Objective C - my code is returning nulls for the lower level object values - userid, FirstName and LastName

The complete JSON is:

{
  "members" :
    [
      {"member" : {"userid":"1","FirstName":"ramesh","LastName":"babu"}},
      {"member" : {"userid":"2","FirstName":"ramesh2","LastName":"babu2"}},
      {"member" : {"userid":"3","FirstName":"ramesh3","LastName":"babu3"}}
    ]
}

My code is:

- (void)viewDidLoad
{
    [super viewDidLoad];

    dispatch_async(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL: kLatestKivaLoansURL];
        [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
    });
}

- (void)fetchedData:(NSData *)responseData {
    //parse out the json data
    NSError* error;
    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
                                                         options:kNilOptions 
                                                           error:&error];

    NSArray* members = [json objectForKey:@"members"]; //2


    NSString *text1 = [json description];
    jsonSummary.text = text1;

    NSEnumerator *e = [members objectEnumerator];
    NSArray *keys = [NSArray arrayWithObjects:@"userid", @"FirstName", @"LastName", nil];

    NSDictionary * member;
    while (member  = (NSDictionary *)[e nextObject]) {
        // do something with object
        // Iterate it
        text1 = [member description];
        NSLog(@"MEMBER ROW DATA%@", text1);
        for (id key in keys) {

            text1 = [member description];
            NSLog(@"key: %@   value:%@ ", key, [member objectForKey:key]);

        }

    }
}

Any help would be appreciated!!

1 Answer 1

1

According to the sample JSON data, the "members" array contains dictionaries that each have a single key "member". The "member" key's value contains the dictionary with the lower level member data.

Your code assumes that the dictionaries with the lower level values are the array elements but they're not.

You need to first get to the "member" key value and then get the lower level values.

Changing this line:

NSLog(@"key: %@   value:%@ ", key, [member objectForKey:key]);

to:

NSLog(@"key: %@   value:%@ ", key, 
    [[member objectForKey:@"member"] objectForKey:key]);

should do it though I'd change the variable names a bit to make it less confusing.

Sign up to request clarification or add additional context in comments.

1 Comment

Anna, Thanks, I got the key values and found that member dictionar y has 'member' object inside it. The following is the code that worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.