Getting values ​​from json using objective-c

I'm currently trying to work with json and objective-c, but with a bit of difficulty. Below is json that returns

{
    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 can verify that the response is returned, and the key is sethostname, but no matter what I try, I can not get, for example, the status or statusmsg value. Can someone point me to the right place. Below is the base code that I use to check if sethostname is being 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");
}
+5
source share
3 answers

If in doubt, write down the JSON data structure. For instance:

{
    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 =             (
        );
    });
}

( NeXTSTEP) , . sethostname, . , : msgs, status, statusmsg, warns. msgs , status , statusmsg , warns` :

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

, :

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"];

}
+11

JSON - [myString jsonValue];

JSON framework objective-c

+1

, if ([arr containsObject:@"sethostname"]) , . , SAME.

As jtbandes wrote, you need to write the actual output. NSLog res and arr and see what you have.

0
source

All Articles