user4038028
user4038028

Reputation:

Parse JSON array in Objective-C

I have managed to extract the following array (which I am dumping to console) from some json. How can I get and print out the value for one of the elements, i.e. task?

Objective-C:

NSArray *array = [dict objectForKey:@"row"];
        NSLog(@"array is: %@",array);

Console output:

array is: {
    0 = 1;
    1 = "send email";
    2 = "with attachment";
    ltask = "with attachment";
    task = "send email";
    userid = 1;
}

Upvotes: 0

Views: 1017

Answers (4)

Ptbaileys
Ptbaileys

Reputation: 41

try

        if ([[dictionary allKeys] containsObject:@"row"]) {
            NSObject *objRow = dictionary[@"row"];
            if(objRow){
                if([objRow isKindOfClass:[NSArray class]]){
                     NSArray *arr = (NSArray *)objRow;
                     ....
                }
                if([objRow isKindOfClass:[NSDictionary class]]){
                     NSDictionary *dic = (NSDictionary *)objRow;
                     ....
                }
            }
        }

Upvotes: 0

Suhit Patil
Suhit Patil

Reputation: 12023

From the log, it looks like the output is an NSDictionary object, so to get the value of task key just do this

NSDictionary *myDict = dict[@"row"];
NSString *task = myDict[@"task"];
NSLog(@"task = %@", task);

if you want to confirm just check the class type using isKindOfClass: method

if([dict[@"row"] isKindOfClass:[NSDictionary class]]) {

    NSDictionary *myDict = dict[@"row"];
    NSString *task = myDict[@"task"];
    NSLog(@"task = %@", task);

} else if([dict[@"row"] isKindOfClass:[NSArray class]]) {

    NSArray *myArray = dict[@"row"];
    NSDictionary *myDict = myArray[0];
    NSString *task = myDict[@"task"];  
    NSLog(@"task = %@", task);

}

Upvotes: 0

Subbu
Subbu

Reputation: 2146

the variable array doesn't seem to be NSArray . Does this work for you?

    id  array = [dict objectForKey:@"row"];

    if([array isKindOfClass:[NSDictionary class]]){
        NSLog(@"Value of task %@",array[@"task"]);
    }

Upvotes: 0

keithbhunter
keithbhunter

Reputation: 12334

array looks like it is actually an NSDictionary, so reference the key to get the value for it.

NSLog(@"Task: %@", array[@"task"]);

Upvotes: 3

Related Questions