JSON解析---初识

JSONJavaScript Object Notation

     是一种轻量级的数据交换格式

     全然独立于语言的文本格式

     易于人阅读和编写

     易于解析和生成 (网络传输速度快)


JSON语法规则

     数据在 名称/ 对中

     数据有逗号分隔

     花括号保存对象

     方括号保存数组




下面是一个.JSON 文件


{

    "class1":[

          {

            "name":"zhangsan",

            "age":"14",

            "tel":"123123123"

          },

         

         {

           "name":"lisi",

           "age":"13",

           "tel":"123123123"

         },

         

         {

           "name":"wangwu",

           "age":"12",

           "tel":"123123123"

         }


    ],

    "class2":[

              {

              "name":"zhaoliu",

              "age":"15",

              "tel":"123123123"

              },

              

              {

              "name":"wuwu",

              "age":"16",

              "tel":"123123123"

              },

              

              {

              "name":"liuliu",

              "age":"17",

              "tel":"123123123"

              } 

              ]

}


  ViewController.m文件

//  JSON解析


#import "ViewController.h"

#import "JSONKit.h"


@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    

    NSString * path= [[NSBundle mainBundle] pathForResource:@"test.json" ofType:nil];

    

    NSData * data=[NSData dataWithContentsOfFile:path];

    

//    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

    /*

    //NSLog(@"%@",dic);    //打印整个JSON文件

     */

    

    /*

    NSArray * array=dic[@"class1"];   //拆一层

    NSLog(@"%@",array);

    */

   

    /*

    NSArray * array=dic[@"class1"];

    for(NSDictionary * dic in array)

    {

        NSLog(@"%@",dic);     //拆两层

    }

     */

    

    //得到model

    /*

    NSArray * array=dic[@"class1"];   //拆一层

    //NSLog(@"%@",array);

    for( NSDictionary * dic in array)

    {

        NSData * data=[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];

        NSString * str=[[NSString  alloc]initWithData:data encoding:NSUTF8StringEncoding];

        NSLog(@"%@",str);

    }

    */

    

    //打印第一组的人员姓名

    /*

    NSArray * array=dic[@"class1"];   //拆一层

    //NSLog(@"%@",array);

    NSMutableArray * marray=[[NSMutableArray alloc]init];

    for( NSDictionary * dic in array)

    {

        [marray addObject:dic[@"name"]];

    }

    NSLog(@"%@",marray);

    */


//引入JSONKit

    //打印整个JSON文件

    /*

    NSDictionary * dic=[data objectFromJSONData];

    NSLog(@"%@",dic);

    */


    /*

    NSString * str=@"{\"name\":\"zhangsan\"}";

    NSData * datas=[str dataUsingEncoding:NSUTF8StringEncoding];

    id obj=[datas objectFromJSONData];

    NSLog(@"%@",obj);

    */


}


@end


PS:推荐一个站点 www.bejson.com 能够将没有组织结构的.JSON 文件上传。就能够轻松的转变成可视化的视图结构。





posted @ 2016-03-02 17:12  mengfanrong  阅读(187)  评论(0编辑  收藏  举报