首页 > 技术文章 > JSON 序列化 和 JSON 反序列化

xhc1263478959 2015-09-14 19:42 原文

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

        

    }];

}

推荐阅读