iOS开发实践之JSON

来源:互联网 发布:巫师3画面优化设置 编辑:程序博客网 时间:2024/04/28 05:10

   服务器返回给客户端的数据,一般都是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 0
原创粉丝点击