• 序列化与反序列化


    序列化[把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(@"%@
    %@",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"]);
            
        }];
    
  • 相关阅读:
    基于IPV6的数据包分析
    OSPFv3与OSPF的配置
    防火墙技术综合实验
    基于服务器的AAA配置实验
    基于服务器的AAA实验
    ipv6到ipv4隧道6to4(GNS3)
    Intellij IDEA(idea) 设置创建文件自动添加创建人和创建时间
    虎扑盖饭系列的数据爬虫和分析
    优酷评论爬虫
    MySQL聚族索引、辅助索引、回表和索引覆盖
  • 原文地址:https://www.cnblogs.com/xzk-it/p/6540669.html
Copyright © 2020-2023  润新知