Retrieving values from json using objective-c

Peter picture Peter · Aug 20, 2011 · Viewed 11.3k times · Source

I am currently trying to work with json and objective-c however having a bit of difficulty. The following is the json that is being returned

{
    sethostname =     (
    {
        msgs = "Updating Apache configuration\nUpdating cPanel license...Done. Update succeeded.\nBuilding global cache for cpanel...Done";
        status = 1;
        statusmsg = "Hostname Changed to: a.host.name.com";
        warns =             (
        );
    });
}

I am able to check that the response is coming back and the key is sethostname however no matter what I try I cannot get for example the value of status or statusmsg. Can anyone point me in the right location. The following is basic code I am using to check that sethostname is returned.

NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&myError];
NSLog([res description]);
NSArray *arr;
arr = [res allKeys];
if ([arr containsObject:@"sethostname"])
{
    NSLog(@"worked");
}

Answer

user557219 picture user557219 · Aug 21, 2011

When in doubt, write down the structure of your JSON data. For example:

{
    sethostname =     (
    {
        msgs = "Updating Apache configuration\nUpdating cPanel license...Done. Update succeeded.\nBuilding global cache for cpanel...Done";
        status = 1;
        statusmsg = "Hostname Changed to: a.host.name.com";
        warns =             (
        );
    });
}

(which is in NeXTSTEP property list format, actually) means that you have a top-level dictionary. This top-level dictionary contains a key called sethostname whose value is an array. This array is comprised of dictionaries, each dictionary having a set of keys: msgs, status, statusmsg, warns. msgs has a string value, status has a number value, statusmsg has a string value,warns` has an array value:

dictionary (top-level)
    sethostname (array of dictionaries)
        dictionary (array element)
            msgs (string)
            status (number)
            statusmsg (string)
            warns (array)
                ??? (array element)

Having understood this structure, your code should look like:

NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&myError];

if (!res) { // JSON parser failed }

// dictionary (top-level)
if (![res isKindOfClass:[NSDictionary class]]) {
    // JSON parser hasn't returned a dictionary
}

// sethostname (array of dictionaries)
NSArray *setHostNames = [res objectForKey:@"sethostname"];

// dictionary (array element)
for (NSDictionary *setHostName in setHostNames) {
    // status (number)
    NSNumber *status = [setHostName objectForKey:@"status"];

    // statusmsg (string)
    NSString *statusmsg = [setHostName objectForKey:@"statusmsg"];

    …
}