简体   繁体   中英

Parsing JSON using objective - c

Im getting a JSON as below from a web service

data =     {
    following = 1;
};
message = "You are now following";
status = 1;

and I am trying to loop it using the following code (in order to get the value of the "following" key)

    for(NSDictionary *item in datarecieved){
        int placeName = [item valueForKey:@"following"];
        NSLog(@"FOLLOWING VALUE %i", placeName);
    }

But I am getting an exception - "uncaught exception of type NSException"

You have to do like this

for(NSDictionary *item in datarecieved){
        if([item class] == [NSDictionary class])
        {
        int placeName = [item valueForKey:@"following"];
        NSLog(@"FOLLOWING VALUE %i", placeName);
        }
    }

because there are two other key in response and they dosen't contain following key

试试吧

int placeName = [datarecieved[@"data"][@"following"] intValue];

Once you deserialize the JSON it will be NSDictionary , so you don't need to use a loop (unless you need to loop through all keys)

In your case if you just want value for following key, you can do the following

NSNumber *following = [datarecieved valueForKeyPath:@"data.following"];
NSLog(@"FOLLOWING VALUE %@", following);

First of all, you need valid JSON. Look into the OP comments, there is a good address for understanding JSON.

Then you first must parse the JSON data. Assuming datareceived is of class NSData :

NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:datareceived options:nil error:&error];

if(error) {
    NSLog(@"parsing error: %@", error);
}
else {
    for(NSString *key in [dict allKeys]) {
        NSLog(@"%@ = %@", key, [dict objectForKey:key]);
    }
}

The exception you are doubtless getting is unrecognized selector sent to instance 0x12345678 and is because item does not support that selector.

You need to check that item is actually an NSDictionary before calling valueForKey: (you should be using objectForKey: anyway):

for(NSDictionary *item in datarecieved){
    if ([item isKindOfClass:[NSDictionary class]]) {
        int placeName = [item objectForKey:@"following"];
        NSLog(@"FOLLOWING VALUE %i", placeName);
    }
}

(you probably want to break at some point once you've found what you're looking for as well).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM