json的序列化

那年仲夏 提交于 2020-04-07 03:47:48

// json序列化的条件:

    // 1.The top level object is an NSArray or NSDictionary.(数据的最外层必须是数组或字典)

    // 2.All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.(所有对象必须是NSString, NSNumber, NSArray, NSDictionary, or NSNull类型的对象)

    // 3.All dictionary keys are instances of NSString.(字典中的键必须是NSString类型的对象)

    // 4.Numbers are not NaN or infinity.(数据中Numbers不能为空或无穷大)

使用json序列化的几种情况:

1.手动拼接json

   
    NSString *string = @"{\"name\":\"zhangsan\",\"age\":\"26\"}";
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]];


 2.字典

    
    NSDictionary *dict = @{@"name":@"zhangsan",@"age":@"27"};
    // json的序列化(将对象转换为二进制数据)
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];


3.数组

 NSDictionary *dict1 = @{@"name":@"zhangsan",@"age":@"27"};
 NSDictionary *dict2 = @{@"name":@"lisi",@"age":@"28"};
 NSArray *arr = @[dict1,dict2];
 // json的序列化
 NSData *data = [NSJSONSerialization dataWithJSONObject:arr options:0 error:NULL];


4.自定义对象

Person *p1 = [[Person alloc] init];
p1.name = @"zhangsan";
p1.age = 24;
[p1 setValue:@(YES) forKey:@"_isYellow"];

// json的序列化

    // 这种方式是错误的,运行的时候会崩的,因为这中数据不符合json序列化的条件

    // json序列化的条件:

    // 1.The top level object is an NSArray or NSDictionary.

    // 2.All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.

    // 3.All dictionary keys are instances of NSString.

    // 4.Numbers are not NaN or infinity.

NSData *data = [NSJSONSerialization dataWithJSONObject:p1 options:0 error:NULL];

//正确的写法:

// 对象转字典
   NSDictionary *dict = [p1 dictionaryWithValuesForKeys:@[@"name",@"age",@"_isYellow"]];
// json序列化
   NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];


5.集合


    
    Person *p1 = [[Person alloc] init];
    p1.name = @"zhangsan";
    p1.age = 24;
    [p1 setValue:@(YES) forKey:@"_isYellow"];
    
    Person *p2 = [[Person alloc] init];
    p2.name = @"lisi";
    p2.age = 25;
    [p2 setValue:@(NO) forKey:@"_isYellow"];
    
    NSArray *arr = @[p1,p2];
    
    // 遍历:将数组中的对象转换为字典
    NSMutableArray *mutArr = [NSMutableArray array];
    [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary *dict = [obj dictionaryWithValuesForKeys:@[@"name",@"age",@"_isYellow"]];
        [mutArr addObject:dict];
    }];
    
    // json的序列化
    NSData *data = [NSJSONSerialization dataWithJSONObject:mutArr options:0 error:NULL];







易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!