网络篇-NSJSONSerialization转JSON

简介json

  • NSJSONSerialization数组

    介绍:
        在了解NSJSONSerialization以前咱们须要知道JSON这个东西,JSON是什么呢!是一种轻量级的数据交换格式,更能够
        理解为后台服务器传来的奇怪数据,然而NSJSONSerialization就是能够解开这个奇怪数据的方法,其实解开的方法有
        不少,如:TouchJSON、SBJSON、JSONKit等等,可是NSJSONSerialization是苹果自家开发,因此性能方面的话应该
        就不用说了,毕竟是亲生的,可是用什么仍是处决大家本身,,这里的话我主推NSJSONSerialization
    
    经常使用方法:
        一、json数据转OC对象
            + (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
        二、OC对象数据转json
            + (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;
  • 一、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"]);
        }];
    }
  • 二、NSDictionary转JSON异步

    /*
        字典转JSON
    */
    -(void)DictToJson{
        //一、建立一个NSDictionary
        NSDictionary *dict = @{
                    @"Name":@"LitterL",
                    @"Age":@"20"
                    };
        //二、判断是否能转为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];
    url

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

相关文章
相关标签/搜索