网络篇-NSJSONSerialization转JSON

简介

  • NSJSONSerialization

    介绍:
        在了解NSJSONSerialization之前我们需要知道JSON这个东西,JSON是什么呢!是一种轻量级的数据交换格式,更可以
        理解为后台服务器传来的奇怪数据,然而NSJSONSerialization就是可以解开这个奇怪数据的方法,其实解开的方法有
        很多,如:TouchJSON、SBJSON、JSONKit等等,但是NSJSONSerialization是苹果自家开发,所以性能方面的话应该
        就不用说了,毕竟是亲生的,但是用什么还是处决你们自己,,这里的话我主推NSJSONSerialization
    
    常用方法:
        1、json数据转OC对象
            + (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
        2、OC对象数据转json
            + (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;
    
    
  • 1、JSON转NSDictionary

    /*
        JSON转字典
    */
    -(void)jsonToDict{
        //创建URL对象
        NSURL *url = [NSURL URLWithString:@"http://192.168.1.0:8080/login?username=LitterL&pwd=123&type=JSON"];
        //创建请求
        NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
        //发送异步请求
        [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            /*
             第一个参数:要解析的二进制数据
             第二个参数:解析json的选项
                NSJSONReadingMutableContainers = (1UL << 0), 最外层是可变的字典和数组
                NSJSONReadingMutableLeaves = (1UL << 1),     里面的字符串也是可变的,iOS7
                NSJSONReadingAllowFragments = (1UL << 2)     最外层既不是字典也不是数组
                kNilOptions为什么都没有
             第三个参数:错误信息
             */
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    
            NSLog(@"字典为--------%@",dict);
            NSLog(@"字典中的success为-------------%@",dict[@"success"]);
        }];
    }
    
  • 2、NSDictionary转JSON

    /*
        字典转JSON
    */
    -(void)DictToJson{
        //1、创建一个NSDictionary
        NSDictionary *dict = @{
                    @"Name":@"LitterL",
                    @"Age":@"20"
                    };
        //2、判断是否能转为Json数据
        BOOL isValidJSONObject =  [NSJSONSerialization isValidJSONObject:dict];
        if (isValidJSONObject) {
            /*
             第一个参数:OC对象 也就是我们dict
             第二个参数:
                NSJSONWritingPrettyPrinted 排版
                kNilOptions 什么也不做
             */
            NSData *data =  [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
            //打印JSON数据
            NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        }
    }
    

    这里的话是排版了的

    这里的话是没有排版的,需更改:(大家自行对照)
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:nil];

    补充:
    至于转模型的话与转字典差不多,所以的话这里我便不上代码了,写了这篇文章之后应该要等十多天才能在上码了。因为要去出差了,不知道广州天气怎么样,有码友告知吗

posted @ 2016-01-15 10:54  周大萌的萌  阅读(3844)  评论(0编辑  收藏  举报