JSON 序列化 和 JSON 還原序列化

來源:互聯網
上載者:User

標籤:

// JSON 序列化 (OC 資料轉換成 JSON 資料)

- (void)json

{

    

    // 序列化:將OC資料類型轉換成json資料類型.

    // 只有數組/字典才可以轉換成 json 資料.

    

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

    

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

    

    // 將字典轉換成 json 資料.

    

    if ([NSJSONSerialization isValidJSONObject:array]) { // 判斷 當前對象是否能夠轉換成json資料.

        

        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);

        

    }];

}

JSON 序列化 和 JSON 還原序列化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.