iOS JSON序列化与反序列化

简介: 从本地发送JSON数据到服务器// 创建JSON- (NSData *)createJSON { // 1. 自己拼JSON形式字符串 NSString *jsonStr1 = @"{\"name\":\"zhangsan\",...
  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);
    
}
目录
相关文章
|
2月前
|
存储 XML JSON
数据传输的艺术:深入探讨序列化与反序列化
数据传输的艺术:深入探讨序列化与反序列化
59 0
|
1月前
|
JSON 安全 Java
Spring Boot 序列化、反序列化
本文介绍了Spring Boot中的序列化和反序列化。Java提供默认序列化机制,通过实现Serializable接口实现对象到字节流的转换。Spring Boot默认使用Jackson处理JSON,可通过注解和配置自定义规则。然而,序列化可能引发安全问题,建议使用白名单、数据校验和安全库。最佳实践包括使用标准机制、自定义规则及注意版本控制。文章还提醒关注性能并提供了相关参考资料。
45 2
|
1天前
|
XML 存储 JSON
c#XML、JSON的序列化和反序列化,看完你就懂了
c#XML、JSON的序列化和反序列化,看完你就懂了
6 0
|
2天前
|
JSON Java Linux
【探索Linux】P.30(序列化和反序列化 | JSON序列化库 [ C++ ] )
【探索Linux】P.30(序列化和反序列化 | JSON序列化库 [ C++ ] )
19 2
|
4天前
|
XML 存储 JSON
[计算机网络]---序列化和反序列化
[计算机网络]---序列化和反序列化
|
11天前
|
存储 JSON PHP
python序列化与反序列化
python序列化与反序列化
|
13天前
|
存储 Java 测试技术
滚雪球学Java(22):序列化和反序列化
【4月更文挑战第11天】🏆本文收录于「滚雪球学Java」专栏,专业攻坚指数级提升,希望能够助你一臂之力,帮你早日登顶实现财富自由🚀;同时,欢迎大家关注&&收藏&&订阅!持续更新中,up!up!up!!
33 1
滚雪球学Java(22):序列化和反序列化
|
14天前
|
JSON 编译器 Go
Golang深入浅出之-结构体标签(Tags):JSON序列化与反射应用
【4月更文挑战第22天】Go语言结构体标签用于添加元信息,常用于JSON序列化和ORM框架。本文聚焦JSON序列化和反射应用,讨论了如何使用`json`标签处理敏感字段、实现`omitempty`、自定义字段名和嵌套结构体。同时,通过反射访问标签信息,但应注意反射可能带来的性能问题。正确使用结构体标签能提升代码质量和安全性。
15 0
|
16天前
|
SQL 存储 安全
每日一道面试题:Java中序列化与反序列化
每日一道面试题:Java中序列化与反序列化
11 0
|
26天前
|
存储 Java
Java输入输出:解释一下序列化和反序列化。
Java中的序列化和反序列化是将对象转换为字节流和反之的过程。ObjectOutputStream用于序列化,ObjectInputStream则用于反序列化。示例展示了如何创建一个实现Serializable接口的Person类,并将其序列化到文件,然后从文件反序列化回Person对象。
28 5