美文网首页
JSON序列化的归纳整理

JSON序列化的归纳整理

作者: 褪而未变 | 来源:发表于2017-09-18 12:57 被阅读0次

JSON的序列化

(一)序列化和反序列化

  • 序列化 : 将 字典或者数组等OC对象 转换成 二进制数据 准备发送给服务器.
  • 反序列化 : 从服务器接收到 二进制数据 转换成 字典或者数组等OC对象.

(二)JSON序列化使用场景

  • 向服务器发送一些信息时,比如,发微博...

  • 我们可以将描述信息定义成JSON字符串,字典或者数组,再将其序列化成二进制形式的JSON字符串,发送给服务器,服务器接收到之后,可以直接反序列化成JSON字符串,字典或者数组.

  • 当我们需要向服务器发送一个OC对象时,可以将OC对象转换成二进制形式的JSON字符串.因为服务器不认识OC对象,不能直接发送.

(三)序列化字典和数组

1.发送JSON数据到服务器

  • 方案一 : 把JSON格式的字符串序列化成JSON的二进制
#pragma 方案一 : 把JSON格式的字符串序列化成JSON的二进制
- (void)POSTJSON_01
{
    NSString *jsonStr = @"{\"name\":\"大发明家\"}";

    // 把JSON格式的字符串序列化成JSON的二进制
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    [self postJsonWith:jsonData];
}
  • 方案二 : 把字典序列化成JSON格式的二进制
#pragma 方案二 : 把字典序列化成JSON格式的二进制
- (void)POSTJSON_02
{
    NSDictionary *dict = [NSDictionary dictionaryWithObject:@"亚索" forKey:@"name"];

    // 把字典序列化成JSON格式的二进制
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
    [self postJsonWith:jsonData];
}
  • 方案三 : 把数组序列化成JSON格式的二进制
#pragma 方案三 : 把数组序列化成JSON格式的二进制
- (void)POSTJSON_03
{
    NSDictionary *dict1 = [NSDictionary dictionaryWithObject:@"牛头" forKey:@"name"];
    NSDictionary *dict2 = [NSDictionary dictionaryWithObject:@"石头人" forKey:@"name"];
    NSArray *arr = @[dict1,dict2];

    // 把数组序列化成JSON格式的二进制
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:0 error:NULL];
    [self postJsonWith:jsonData];
}

2.发送json数据到服务器的主方法,传入json数据的二进制

#pragma 发送json数据到服务器的主方法,传入json数据的二进制
- (void)postJsonWith:(NSData *)jsonData
{
    // URL
    NSURL *URL = [NSURL URLWithString:@"http://localhost/php/upload/postjson.php"];
    // 请求
    NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:URL];
    // 设置请求方法
    requestM.HTTPMethod = @"POST";
    // 设置请求体
    requestM.HTTPBody = jsonData;

    // 发送请求
    [[[NSURLSession sharedSession] dataTaskWithRequest:requestM completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        // 处理响应
        if (error == nil && data != nil) {

            // 反序列化
            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",str);

        } else {
            NSLog(@"%@",error);
        }
    }] resume];
}

(四)序列化自定义对象

1.准备Person类

  • Person类.h文件
@interface Person : NSObject

/// 姓名
@property (nonatomic,copy) NSString *name;

@end
  • Person类.m文件
@implementation Person {
    /// 年龄
    NSString *_age;
}

@end
  • 方案四 : 自定义对象序列化成JSON格式的二进制
#pragma 方案四 : 自定义对象序列化成JSON格式的二进制
- (void)POSTJSON_04
{
    Person *p = [[Person alloc] init];

    // 给对象属性或者私有成员变量赋值
    p.name = @"张小厨zxc";
    [p setValue:@"18" forKey:@"_age"];

    // 先把对象转成字典
    NSDictionary *dict = [p dictionaryWithValuesForKeys:@[@"name",@"_age"]];
    // 再把字典序列化成JSON格式的二进制
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
    [self postJsonWith:jsonData];
}

2.发送json数据到服务器的主方法,传入json数据的二进制

#pragma 发送json数据到服务器的主方法,传入json数据的二进制
- (void)postJsonWith:(NSData *)jsonData
{
    // URL
    NSURL *URL = [NSURL URLWithString:@"http://localhost/php/upload/postjson.php"];
    // 请求
    NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:URL];
    // 设置请求方法
    requestM.HTTPMethod = @"POST";
    // 设置请求体
    requestM.HTTPBody = jsonData;

    // 发送请求
    [[[NSURLSession sharedSession] dataTaskWithRequest:requestM completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        // 处理响应
        if (error == nil && data != nil) {

            // 反序列化
            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",str);

        } else {
            NSLog(@"%@",error);
        }
    }] resume];
}

相关文章

网友评论

      本文标题:JSON序列化的归纳整理

      本文链接:https://www.haomeiwen.com/subject/uztbsxtx.html