如果你想把Array和Dictionary序列化为JSON对象以便在网络中传输或者保存到磁盘中,需要使用NSJSONSerialization这个类的dataWithJSONObject:options:error:方法来实现 。NSJSONSerialization这个类的dataWithJSONObject:options:error:方法可以对数组和字典进行序列化,这些数组和字典包含的值为:NSString、NSNumber、NSArray、NSDictionary和代表nil值的NSNull。传递到这个方法中的参数要么是数组要么是字典
下面我们来创建一个简单的数组:包含一些键值:
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithDictionary
@"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"];
如上代码所示,这个字典包含 first name,last name 和 Anthony Robbins 的年龄。在字典 中有一个key 的名称为 children,这个 key 对应着一个数组——Anthony 的孩子。数组中的 字符串代表了Anthony 的孩子。至此,字典中已经包含了我们希望的所有内容。现在是时候 将其序列化为 JSON对象了:
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrint
error:&error];
if ([jsonData length] > 0 &&error == nil){
NSLog(@"Successfully serialized the dictionary into data = %@", jsonData);
}
else if ([jsonData length] == 0 &&error == nil){
NSLog(@"No data was returned after serialization.");
}
else if (error != nil){
NSLog(@"An error happened = %@", error);
}
如上代码 dataWithJSONObject:options:error:这个方法将会返回一个 NSData 类型的数 据,而你可以很简单的把这个数据转化成一个 NString 类型的,然后把他打印在控制台上以 便测试查看。如下代码是一个完整的实例:
NSMutableDictionary *dictionary =
[NSMutableDictionary dictionaryWithDictionary
@"First Name" : @"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"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrint
error:&error];
if ([jsonData length] > 0 &&error == nil)
{
NSLog(@"Successfully serialized the dictionary into data.");
NSString *jsonString =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"JSON String = %@", jsonString);
}
else if ([jsonData length] == 0 &&error == nil)
{
NSLog(@"No data was returned after serialization."); }
else if (error != nil)
{
NSLog(@"An error happened = %@", error);
}