Search code examples
iosjsonnsarraynsdictionarynsmutabledictionary

Checking for zero length array from JSON set


I have JSON data set returned that I am parsing.

If the data contains a record it looks like this:

dictData: {
    Recordset =     (
                {
            Record = (
                                {
                    MyDate = "2016-06-15 11:04:43";
                    MyID = 53070;
                    SomeDescription = "";

                }
            );
        }
    );
}

If the data does NOT contains a record it looks like this: Notice the "" in the return set which is causing me issues.

dictData: {
    Recordset =     (
        ""
    );
}

I am having trouble accounting for the zero length array in the Recordset.

Here is my base code for parsing the data.

NSDictionary * dictData = [NSDictionary dictionaryWithDictionary:[someOtherDictionary objectForKey:@"Data"]];
NSArray * arrRecordSet  = [dictData objectForKey:@"Recordset"];

if([arrRecordSet objectAtIndex:0] != nil) {
    NSLog(@"CONTAINS RECORDS");
    //Do something with the records
}
else {
    NSLog(@"DOES NOT CONTAIN RECORDS");
}

I have tried various iterations of things like checking if [arrRecordSet objectAtIndex:0] length is greater than zero or checking the count size.

I think the double quotes are throwing me off.

Any help?

UPDATE

RAW JSON as requested

ONE RECORD

{
    APIResponse =     {
        Data =         {
            Recordset =             (
                                {
                    Record =                     (
                                                {
                            MyDate = "2016-06-15 11:04:43";
                            MyID = 53070;
                            SomeDescription = "";
                        }
                    );
                }
            );
        };
    };
}

NO RECORDS

{
    APIResponse =     {
        Data =         {
            Recordset =  (
                               ""
            );
        };
    };
}

Solution

  • So in the case of success the Recordset value is an array with a dictionary and in the case of failure the Recordset value is an array with a string.

    So:

    NSArray *recordSet = response[@"APIResponse"][@"Data"][@"Recordset"];
    if ([recordSet count] > 0 &&
        [recordSet[0] isKindOfClass:[NSDictionary class]]) {
        // Success
        NSDictionary *record = recordSet[0];
        ...
    } else {
        // Failure
    }