序列化与反序列化
序列化[把OC对象序列化为有特殊格式的字符串]
用类NSJSONSerialization可以对oc和josn对象进行转换
NSDictionary *dict = @{
@"name":@"xiaomage",
@"age" :@18
};
NSArray *arrM = @[@"123",@"456"];
NSString *str = @"xiaomage";
/*
- Top level object is an NSArray or NSDictionary
顶层必须是字典或者是数组
- All objects are NSString, NSNumber, NSArray, NSDictionary, or NSNull
- All dictionary keys are NSStrings
- NSNumbers are not NaN or infinity
null ----- NSNull
*/
BOOL isValid = [NSJSONSerialization isValidJSONObject:str];
if (isValid) {
//OC---->jsoN
//NSJSONWritingPrettyPrinted 排版
NSData *data = [NSJSONSerialization dataWithJSONObject:str options:NSJSONWritingPrettyPrinted error:nil];
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@\n%@",result,arrM);
}else
{
NSLog(@"不能转换");
}
反序列化[把JSON字符串反序列化为OC的对象]
//1.确定请求路径
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=abc&type=JSON"];
//2.创建请求对象uc
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.发送GET请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//{"error":"用户名不存在"}
// "error"
//4.解析数据
/*
第一个参数:要解析的二进制数据(json)
第二个参数:
NSJSONReadingMutableContainers = (1UL << 0), 表示时一个可变的数组或者是字典
NSJSONReadingMutableLeaves = (1UL << 1), 字符串也是可变 iOS7有问题
NSJSONReadingAllowFragments = (1UL << 2) 既不是数组也不是字典,必须使用该枚举值
第三个参数:错误信息
*/
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(@"%@",dict[@"error"]);
}];