網絡篇-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

相關文章
相關標籤/搜索