解析JSON字符串

代码:

#import <Foundation/Foundation.h>





void parseJSON(NSString *text)

{

    NSError *error = nil;

    NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];

    NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

    

    if (error != nil) {

        NSLog(@"has error");

        return;

    }

    

    for (int i=0; i < array.count; i++) {

        

        NSDictionary *dict = array[i];

        id bookid = [dict objectForKey:@"bookid"];

        NSLog(@"bookid = %d", [bookid intValue]);

        NSString *name = [dict objectForKey:@"name"];

        NSLog(@"name = %@", name);

    }

}



int main(int argc, const char * argv[])

{

    @autoreleasepool {

        parseJSON(@"[{\"bookid\":123,\"name\":\"笑傲江湖\"}]");

    }

    return 0;

}

 

你可能感兴趣的:(json)