Question

I am getting server response and parsing as below for my synchronous request.

NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonError];
NSLog(@"responseDict: %@", responseDict);

The result is below:

responseDict: {
d =     {
    Datavalue = 1;
    "__type" = "Response:#DummyAPI";
    response = OK;
};

I am trying to parse the above result, if it is "OK" then I want to store the "Datavalue" somewhere.. I am trying like below,

-(void) handleResponse :(NSDictionary *) responsedata // it is being passed from caller
{
    NSString* value = NULL;

    for (id key in responsedata)
    {
        value = (NSString*)[responsedata objectForKey:@"response"];

        if ( [value isEqualToString:@"OK"] )
        {
            NSLog(@"RESPONSE SUCCESS, need to store data value");
        }
        else
        {
            NSLog(@"INVALID RESPONSE");
        }
    }
}

But, it is always printing "INVALID RESPONSE", but I got response as "OK". What am I doing wrong here? Please advise!

Thank you!

Was it helpful?

Solution

You are missing a level of nesting in the dictionaries you received back. Your response shows that responseData contains a key called "d" whose value is another dictionary, and that dictionary is what has a key called "response"

Because you are working inside a loop, I will assume that your response can contain multiple values at the top level and not just "d", and that you are trying to loop through each of those. Based on that assumption you probably want something like this:

-(void) handleResponse :(NSDictionary *) responsedata // it is being passed from caller
{
    NSString* value = NULL;

    for (id key in responsedata)
    {
        NSDictionary *currentDict = (NSDictionary *) [responseData objectForKey:key];
        value = (NSString*)[currentDict objectForKey:@"response"];

        if ( [value isEqualToString:@"OK"] )
        {
            NSLog(@"RESPONSE SUCCESS, need to store data value");
        }
        else
        {
            NSLog(@"INVALID RESPONSE");
        }
    }
}

OTHER TIPS

Seems weird to me and probably is not the problem but:

value = (NSString*)[responsedata objectForKey:@"response"];

if ( [value isEqualToString:@"OK"] ){
    NSLog(@"RESPONSE SUCCESS, need to store data value");
}
else{
    NSLog(@"INVALID RESPONSE");
}

That shouldn't been done inside a for loop. Just try that code outside the for loop, it should work. Other thing you might want to try doing is calling the isKindOfClass method over the value for @"response" and you should get something saying it is a string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top