iOS开发实践之JSON

   服务器返回给客户端的数据,一般都是JSON格式或者XML格式(文件下载除外),JSON和XML的比较这里不详述,可以参考这文章http://www.cnblogs.com/SanMaoSpace/p/3139186.html 。  总的来说XML文件庞大,文件格式复杂,解析需要花费较多的资源和时间,传输占带宽。JSON数据格式比较简单,易于读写,格式都是压缩的,占用带宽小,移动开发首选。

  JSON:

1、JSON的格式很像OC中的字典和数组

{"name" : "jack", "age" : 10}
{"names" : ["jack", "rose", "jim"]}
标准JSON格式的注意点:key必须用双引号

JSON – OC 转换对照表:



2、在iOS中,JSON的常见解析方案有4种
     第三方框架:JSONKitSBJsonTouchJSON(性能从左到右,越差) 
     苹果原生(自带):NSJSONSerialization性能最好


NSJSONSerialization的常见方法:
 2.1、JSON 转 OC对象(其中的过程是json转换为字典,字典再转换为对象)
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;

例子: 请求服务器,返回json数据。json数据封装到数组对象中。

服务器返回数据json格式:


- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/myService/video"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError || data==nil) {
            [MBProgressHUD showError:@"网络繁忙,请稍后再试!"];
            return ;
        }
        
        //json 转化为data 得到字典
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        //取出字典中的某一个key
        NSArray *videoArray = dict[@"videos"];
        //字典转模型
        for (NSDictionary *videoDict in videoArray) {
            //字典转模型(对象)
            Video *video = [Video videoWithDict:videoDict];
            [self.videos addObject:video];
        }
      
    }];
    
 }


 2.2、OC对象 转JSON数据 (对象转字典,字典再转json)
+ (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;


#import "ViewController.h"
#import "Person.h"

@interface ViewController ()
@property(nonatomic,strong) Person *person;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _person = [[Person alloc]init];
    _person.name = @"kobe";
    _person.age = 24;
    _person.sex = @"男";
    _person.phone = @"1112334444";
    
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //person 转字典
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"age"] = [NSString stringWithFormat:@"%d",self.person.age];
    dict[@"name"] = self.person.name;
    dict[@"sex"] = self.person.sex;
    dict[@"phone"] = self.person.phone;
  
    NSData *data =  [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",dataStr);
    
    
}

@end
结果:

 {
  "age" : "24",
  "sex" : "男",
  "phone" : "1112334444",
  "name" : "kobe"
}


NSJSONReadingOptions枚举:

NSJSONReadingMutableContainers:返回可变容器,NSMutableDictionary或NSMutableArray。 
NSJSONReadingMutableLeaves:返回的JSON对象中字符串的值为NSMutableString 
NSJSONReadingAllowFragments:允许JSON字符串最外层既不是NSArray也不是NSDictionary,但必须是有效的JSON Fragment。
NSJSONWritingPrettyPrinted:的意思是将生成的json数据格式化输出,这样可读性高,不设置则输出的json字符串就是一整行。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值