关于iOS数据操作方式详解(二)— Jason数据解析

  作为数据解析的另外一种方式,Jason在当前的程序设计中被经常使用到,其干净整洁的数据结构,简洁的数据处理方法被大多数人所接受,那么现在我们来了解一下对于Jason数据的处理解析方法:

  同样的首先我们给出一个Jason文件的部分内容: 

[{
  "phone": [
            "12345678",
            "87654321"
            ],
  "name": "qingyun1",
  "age": 100,
  "address": {
  "country": "china",
  "province": "zhengzhou"
  },
  "married": false
  }]

  现在我们的问题是如何将里面的数据解析出来以供我们使用:

  (一) 获取Jason文件的路径

NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"personal" withExtension:@"json"];

  

  (二) 解析出Jason里面的数据存储到数组里,这里可以有两种方法:第三方的JasonKit库和系统提供的Jason解析方式

   第三方的Jason库解析方式:

    NSString *strJson = [[NSString alloc] initWithContentsOfURL:fileUrl encoding:NSUTF8StringEncoding error:nil];
    NSArray *pesons = [strJson objectFromJSONString];

   使用系统提供的Jason解析方式:

 //由于采用系统提供的json解析来, 需要传入的json数据是NSData类型,所以我们需要将文件时在数据读取到内存,并转换为NSData    
  NSData *jsonData = [[NSData alloc] initWithContentsOfURL:fileUrl];   
//     通过使用NSJSONSerialization 的工厂方法, 直接解析json串,
  NSMutableArray * persons = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];

 

  (三) 按照Jason串的结构来解析出具体的数据

//    根据JSON串的结构来解析具体的数据
    for (NSDictionary *jsonResult in persons) {
        NSArray *phoneNumbers = [jsonResult objectForKey:@"phone"];
        for (NSString *number  in phoneNumbers) {
            NSLog(@"phoneNumber is %@",number);
        }
        NSString *name = [jsonResult objectForKey:@"name"];
        NSLog(@"person's name is %@",name);
        
        NSNumber *age = [jsonResult objectForKey:@"age"];
        NSLog(@"person's age is %d",age.intValue);
        
        BOOL isMarried = [[jsonResult objectForKey:@"married"] boolValue];
        NSLog(@"%@",((isMarried) ? @"Married":@"meilaopo"));
NSDictionary
*dicAddress = [jsonResult objectForKey:@"address"]; NSString *strCountry = [dicAddress objectForKey:@"country"]; NSString *strProvince = [dicAddress objectForKey:@"province"]; NSLog(@"person's address is %@, %@",strCountry, strProvince); NSLog(@"-------------------------------------------------------"); }

 

posted @ 2014-05-21 10:31  醉云天  阅读(932)  评论(0编辑  收藏  举报