博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iOS JSON序列化与反序列化
阅读量:7219 次
发布时间:2019-06-29

本文共 3664 字,大约阅读时间需要 12 分钟。

  1. 从本地发送JSON数据到服务器
// 创建JSON- (NSData *)createJSON {    // 1. 自己拼JSON形式字符串    NSString *jsonStr1 = @"{\"name\":\"zhangsan\",\"age\":\"18\"}";    // 转换成二进制数据便于传输    NSData *data = [jsonStr1 dataUsingEncoding:NSUTF8StringEncoding];        // 2. 字典    NSDictionary *dict = @{@"name":@"zhangsan",@"age":@(28)};    NSData *data1 = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];    NSLog(@"%@", dict);        // 3. 数组    NSArray *array = @[                       @{@"name":@"zhangsan",@"age":@(28)},                       @{@"name":@"lilei",@"age":@(20)}                       ];        NSData *data2 = [NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];    NSLog(@"%@", array);        // 4. 自定义对象进行JSON序列化    HMVideo *video1 = [[HMVideo alloc] init];    video1.videoName = @"ll-001.avi";    video1.size = 500;    video1.author = @"mazaiting";    // KVC给成员变量赋值    [video1 setValue:@(NO) forKey:@"_isYellow"];    NSLog(@"%@", video1);        // 自定义对象不能直接序列化,必须先把自定义对象转换成字典或者数组//    if (![NSJSONSerialization isValidJSONObject:video1]) {//        NSLog(@"自定义对象不能序列化");//        return nil;//    }        NSDictionary *dict1 = [video1 dictionaryWithValuesForKeys:@[@"videoName",@"size",@"author",@"_isYellow"]];    NSData *data3 = [NSJSONSerialization dataWithJSONObject:dict1 options:0 error:NULL];    NSLog(@"%@", dict1);        // 5. 自定义对象的数组进行JSON序列化    HMVideo *video2 = [[HMVideo alloc] init];    video2.videoName = @"ll-002.avi";    video2.size = 502;    video2.author = @"mazaiting";    // KVC给成员变量赋值    [video2 setValue:@(NO) forKey:@"_isYellow"];        HMVideo *video3 = [[HMVideo alloc] init];    video3.videoName = @"ll-003.avi";    video3.size = 503;    video3.author = @"mazaiting";    // KVC给成员变量赋值    [video3 setValue:@(YES) forKey:@"_isYellow"];        NSArray *array1 = @[video2, video3];        NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:2];    for (HMVideo *video in array1) {        NSDictionary *dict = [video dictionaryWithValuesForKeys:@[@"videoName",@"size",@"author",@"_isYellow"]];        [mArray addObject:dict];    }    NSData *data4 = [NSJSONSerialization dataWithJSONObject:mArray options:0 error:NULL];            return data4;}// 发送网络数据- (void)postJSON {    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/php/upload/postjson.php"];    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];    request.HTTPMethod = @"post";    request.HTTPBody = [self createJSON];    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:     ^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {         if (connectionError) {             NSLog(@"连接错误 %@", connectionError);             return;         }         NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;         if (httpResponse.statusCode == 200 || httpResponse.statusCode == 304) {             // 解析数据             NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];             NSLog(@"%@", str);         } else {             NSLog(@"服务器内部错误");         }     }];}
  1. JSON数据保存到本地及解析
// 解析JSON- (void)resolveJSON {    // 把JSON数据保存到本地文件    NSDictionary *dict = @{@"name":@"zhangsan", @"age":@(18)};    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];    [data writeToFile:@"/Users/mazaiting/Desktop/111.json" atomically:YES];        // 从本地文件读取JSON数据    NSData *data1 = [NSData dataWithContentsOfFile:@"/Users/mazaiting/Desktop/111.json"];    id json = [NSJSONSerialization JSONObjectWithData:data1 options:0 error:NULL];    NSLog(@"%@", json);    }

转载地址:http://bhxym.baihongyu.com/

你可能感兴趣的文章
876. Middle of the Linked List
查看>>
7-8.本地协议
查看>>
Oracle 物理结构(六) 文件-数据文件
查看>>
牛腩新闻系统的公布
查看>>
Sicily 7974. Integer Lists 解题报告
查看>>
创建过的对象的个数
查看>>
关于SQL命令中不等号(!=,<>)
查看>>
MYSQL的初级使用
查看>>
win10下硬盘安装CentOS7
查看>>
DOM 5
查看>>
游戏截屏
查看>>
python冒泡排序
查看>>
Windows系统编程之进程同步试验
查看>>
linux之pid文件
查看>>
LeetCode-106-Construct Binary Tree from Inorder and Postorder Traversal
查看>>
Struts从2.1升级到2.3版本过程
查看>>
QT制作窗口切换的小程序
查看>>
python学习笔记
查看>>
[PHP] debug_backtrace()可以获取到代码的调用路径追踪
查看>>
Ajax 调用方式
查看>>