iOS网络: 把Array和Dictionaries序列化成JSON对象

你想把 Array 和 dictionary 序列化成 JSON 对象。以方便在网络中传输或者保存到磁盘中。 

方案:

使用 NSJSONSerialization 这个类的 dataWithJSONObject:options:error:方法来实现。 

讨论:

NSJSONSerialization 这个类的 dataWithJSONObject:options:error:方法可以对数组和字典进行序列化,这些数组和字典包含的值为:NSString、NSNumber、NSArray、NSDictionary 和代表 nil 值的 NSNull。传递到这个方法中的参数要么是数组要么是字典。 
 

例子:

下面我们来创建一个简单的数组:包含一些键值:
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithDictionary:@{
    @"FirstName":@"Anthony",
    @"Last Name" : @"Robbins",
    @"Age" : @51
    }];
    NSArray *arrayOfAnthonysChildren = @[
                                         @"Anthony's Son 1",
                                         @"Anthony's Daughter 1",
                                         @"Anthony's Son 2",
                                         @"Anthony's Son 3",
                                         @"Anthony's Daughter 2"
                                         ];
    [dictionary setValue:arrayOfAnthonysChildren forKey:@"children"];

将字典序列化为JSON对象

原文地址:https://www.cnblogs.com/safiri/p/4090108.html