JSON 序列化 和 JSON 反序列化

// JSON 序列化 (OC 數據轉換成 JSON 數據)json

- (void)json數組

{服務器

    

    // 序列化:OC數據類型轉換成json數據類型.網絡

    // 只有數組/字典才能夠轉換成 json 數據.app

    

    NSDictionary *dict = @{@"name":@"zhangsan",@"age":@"18",@"sanwei":@"29"};atom

    

    NSArray *array = @[@"zhangsan",@"lisi",@"wangermazi",@"gebilaowang"];url

    

    // 將字典轉換成 json 數據.spa

    

    if ([NSJSONSerialization isValidJSONObject:array]) { // 判斷 當前對象是否可以轉換成json數據.orm

        

        NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];對象

        

        [data writeToFile:@"/Users/apple/Desktop/array.json" atomically:YES];

        

    }

    

    // 爲何要將 OC 數據轉換成 JSON 數據.

    

    // 通常與服務器作交互的時候,直接傳遞給服務器 json 數據,優勢:1.加快傳輸速率 2.方便服務器開發.

}

 

 

// JSON 反序列化  (json數據轉換成 OC數據)

- (void)jsontest

{

    // 發送網絡請求,獲得 json 數據

    

    // 1.實例化一個網絡請求

    

    NSURL *url = [NSURL URLWithString:@"http://localhost/weather.json"];

    

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    

    // 2.發送網絡請求

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        

        // 網絡請求失敗處理

        if (!data || connectionError) {

            

            NSLog(@"網絡請求失敗,請從新嘗試");

            return ;

        }

        

        NSLog(@"data:%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

        

        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

        

        str = [NSString stringWithFormat:@"{%@}",str];

        

        NSLog(@"%@",str);

        

        NSData *data1 = [str dataUsingEncoding:NSUTF8StringEncoding];

        

        

        // data json格式的二進制數據

        

        // json數據轉換成 OC數據.

        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data1 options:0 error:NULL];

        NSLog(@"dict%@",dict);

        

    }];

}

相關文章
相關標籤/搜索