Search code examples
objective-cjsonnsjsonserialization

Parse JSON String and array with NSJSONSerialization issue?


This is the code i have so far

// Parse data using NSJSONSerialization
NSError *error = nil;
NSArray *JsonArray = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error: &error];
if(!JsonArray)
{
    NSLog(@"Error Parsing Data: %@", error);
}
else
{
    for(NSDictionary *event in JsonArray)
    {
        if([[event description] isEqualToString:@"error"])
        {
            // Get error number? I am confused by this part
            NSLog(@"Element: %@", [event objectForKey:@"error"]);
        }
        else
        {
            NSLog(@"Element: %@", [event description]);
        }
    }
}

this is the JSON Data that parses correctly:

[{data string}, {data strings}]

This only gives me the string "error" and not the int as well:

{"error":0}

I am echoing this data from a PHP script if that helps any. Am i just doing it wrong, or did i miss something?


Solution

  • Your problem is that when you receive an error, you get back an NSDictionary and not an NSArray. This should work:

    if ([jsonObject isKindOfClass:[NSArray class]]) {
        // no error: enumerate objects as you described above
    } else if ([jsonObject isKindOfClass:[NSDictionary class]]) {
        // error: obtain error code
        NSNumber *errCode = jsonObject[@"error"];
    } else {
        // something bad's happening
    }
    

    Stylistic pieces of advice:

    1. Don't call your object JsonArray, since it's not always an array. Call it jsonObject.

    2. Don't start variable names with capital letters.