ios 实现 Array 和 Dictionaries 序列化成 JSON 对象

   如果你想把Array和Dictionary序列化为JSON对象以便在网络中传输或者保存到磁盘中,需要使用NSJSONSerialization这个类的dataWithJSONObject:options:error:方法来实现 。NSJSONSerialization这个类的dataWithJSONObject:options:error:方法可以对数组和字典进行序列化,这些数组和字典包含的值为:NSStringNSNumberNSArrayNSDictionary和代表nil值的NSNull。传递到这个方法中的参数要么是数组要么是字典 


下面我们来创建一个简单的数组:包含一些键值:

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"];

如上代码所示,这个字典包含 first name,last name  Anthony Robbins 的年龄。在字典 中有一个key 的名称为 children,这个 key 对应着一个数组——Anthony 的孩子。数组中的 字符串代表了Anthony 的孩子。至此,字典中已经包含了我们希望的所有内容。现在是时候 将其序列化为 JSON对象了:

NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted
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:NSJSONWritingPrettyPrinted
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);

} 



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值