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

本文介绍如何使用NSJSONSerialization类的dataWithJSONObject:options:error:方法将包含特定类型数据的数组和字典序列化为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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值