JSON是一种轻量级的数据格式,一般用于数据的交互,用于从服务器端向客户端传输数据;
客户端拿到JSON数据后,需要对JSON进行解析,将JSON数据转换为OC数据类型;
JSON转OC的对照表:
大括号{} <=> NSDictionary
中括号[]<=> NSArray
双引号“” <=> NSString
数字 <=> NSNumber
IOS中JSON解析方法有点多种,一般用苹果原生的NSJSONSeralization:
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//NSJSONReadingMutableContainers = (1UL << 0), 返回一个可变的容器
//NSJSONReadingMutableLeaves = (1UL << 1), 返回的里边的数组也是可变数组
//NSJSONReadingAllowFragments // 允许返回的不是正规的数组或者字典
//kNilOptions 不会生成可变对象,效率比较高
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];// 将服务器返回的data,通过 NSJSONSerialization转为OC对象,
NSLog(@"%@",dict);//
}];
// 将OC对象转为JSON,JSON转为字符串,
NSData *data = [NSJSONSerialization dataWithJSONObject:@{@"name" : @"jack", @"age" : @10 } options:NSJSONWritingPrettyPrinted error:nil];//OC对象转化为JSON
NSLog(@"1%@",data);
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; // JSON转为字符串
NSLog(@"%@",str);