初识JSON解析(iOS)

什么是JSON?

JSON : JavaScript Object Notation (JavaScript的对象标记符)
JSON采用完全独立于语言的文本格式
在实际开发中经常使用JSON来获取服务器上的数据,并通过解析json数据获取我们想要的数据。

对于JSON格式的数据来说都是以键值对的形式存在的。
键(key)是用来描述值(value)的意义的,可以通过任意的键找到相应的值。


键值对.png

以JSON格式来写出键和值
"name"是键 "李四"是值,键与值之间用 " : " 隔开,两个键值对之间用 " , " 隔开,两头以大括号开头以大括号结尾。
除此之外还能进行key-value的嵌套。如,key "user"所对应的value是一个整体,在这个value中还有相对应的key-value。


JSON本质.png

从本质上讲JSON格式的数据就是字符串,JSON格式的数据解析就是对字符串的语义分析。
JSON语义分析.png

以一段天气信息为例,将其转换为JSON格式的数据。天气信息作为一个key,内容作为value,而内容中又有相对应的键值对。
JSON实例.png

iOS中的JSON

iOS 5开始苹果公司开始提供自己的JSON库 原生JSON解析库:iOS 5+
第三方JSON库:TouchJson SBJson JSONKit
iOS原生JSON库只支持iOS 5及以上的版本,诺要支持iOS 5以下的版本则需要引入第三方库。因为现在已经是iOS 11了,所以我们用自带的JSON库来学习一下。

实例

iOS 5+ 自带JSON操作库
数据解析:
要求:分别解析以下json库
1.{"name":"James","age":"30"}
2.{"user":{"name":"Kobe","age":"30"}}
3.[{"name":"Curry"},{"name":"Thompson"}]
4.{"user":[{"name":"Pual"},{"name":"Harden"}]}
目的:掌握通过NSJSONSerialization类解析JSON数据
重点:掌握静态函数JSONObjectWithData:option:error:的使用
先在storyboard放一个TextView用来显示解析出来的数据,再放一个button


image.png
- (IBAction)button:(id)sender {
NSString *jsonstr = @"{\"name\":\"James\",\"age\":\"30\"}";//这里需要给双引号添加转义字符否则会报错
NSData * jsonDate = [jsonstr dataUsingEncoding:NSUTF8StringEncoding];//把jsonstr转换成NSData格式的数据
id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonDate options:NSJSONReadingAllowFragments error:nil];
if ([jsonObj isKindOfClass:[NSDictionary class]]) {//字典类型数据会走到这里  
        NSDictionary *dic = (NSDictionary *)jsonObj; //转成字典的对象
        //通过键获取值显示在textview中 stringByAppendingString将字符串接到原有的字符串后面
        _TextView.text = [_TextView.text stringByAppendingString:@"\n"];//这是一个回车
        _TextView.text = [_TextView.text stringByAppendingString:[dic objectForKey:@"name"]];
        _TextView.text = [_TextView.text stringByAppendingString:@"\n"];
        _TextView.text = [_TextView.text stringByAppendingString:[dic objectForKey:@"age"]];
}
if ([jsonObj isKindOfClass:[NSArray class]]) {//数组类型的数据会走到这里
}
}
image.png

2.{"user":{"name":"Kobe","age":"30"}} 有两层所以要解析两次
NSString *jsonTreeStr = @"{\"user\":{\"name\":\"Kobe\",\"age\":\"25\"}}";
NSData * jsonDate = [jsonTreeStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dic1 = [dic objectForKey:@"user"];//加一次解析
_TextView.text = [_TextView.text stringByAppendingString:[dic1 objectForKey:@"name"]];//dic改成dic1
3.[{"name":"Curry"},{"name":"Thompson"}] 数组形式的
NSString *jsonArrStr = @"[{\"name\":\"Curry\"},{\"name\":\"Thompson\"}]";
NSData * jsonDate = [jsonArrStr dataUsingEncoding:NSUTF8StringEncoding];

if ([jsonObj isKindOfClass:[NSArray class]]) {
        //数组类型
        //数据转换:转换成数组
        NSArray *arr = (NSArray *)jsonObj;
        //访问数组中的数据
        for (NSDictionary *dic in arr) {
            _TextView.text = [_TextView.text stringByAppendingString:@"\n"];
            _TextView.text = [_TextView.text stringByAppendingString:[dic objectForKey:@"name"]];
            _TextView.text = [_TextView.text stringByAppendingString:@"\n"];
        }
    }

4.{"user":[{"name":"Pual"},{"name":"Harden"}]} 此时会走到字典类型中,用user获取值,这个值是个数组所以要用for循环取值
NSString *jsonTreeArrStr = @"{\"user\":[{\"name\":\"Pual\"},{\"name\":\"Harden\"}]}";
NSData * jsonDate = [jsonTreeArrStr dataUsingEncoding:NSUTF8StringEncoding];

    if ([jsonObj isKindOfClass:[NSDictionary class]]) {
        //字典类型
        //转成字典的对象
        NSDictionary *dic = (NSDictionary *)jsonObj;
       //jsonTreeArrStr第一层是字典类型 要先那拿到第一层的key 里面的数组用for循环取值
        NSArray *arr = [dic objectForKey:@"user"];
        for (NSDictionary *dic in arr) {
            _TextView.text = [_TextView.text stringByAppendingString:@"\n"];
            _TextView.text = [_TextView.text stringByAppendingString:[dic objectForKey:@"name"]];
            _TextView.text = [_TextView.text stringByAppendingString:@"\n"];
        }
    }

JSON读取文件

数据解析:
要求:1.从文件读取json数据并解析,文件名称weatherinfo.json
2.从网络读取json数据并解析
目的:掌握通过NSJSONSerialization类解析来自文件和网络的json数据
重点:掌握静态函数JSONObjectWIthinkData:options:error:的使用
灵活掌握json数据源的读取技巧

在项目中加入一个json格式的文件


image.png

还是跟上面的案例一样 先在storyboard放一个TextView用来显示解析出来的数据,再放一个button。
代码主体也是没有变化。

- (IBAction)button:(id)sender {
    
    NSString *jsonStr = nil;
    //文件路径
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"weatherinfo" ofType:@"json"];
    //调用系统默认的文件路径
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    //通过函数fileExistaAtPath判断路径下是否存在这个文件
    if ([fileMgr fileExistsAtPath:filePath]) {
        jsonStr = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    }
    else
    {
        _textView.text = @"文件没有找到";
        return;
    }
    
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
    if ([jsonObj isKindOfClass:[NSDictionary class]]) {
        //字典类型
        NSDictionary *dic = (NSDictionary *)jsonObj;
        NSDictionary *dic1 = [dic objectForKey:@"weatherinfo"];
        _textView.text = [_textView.text stringByAppendingString:@"\n"];
        _textView.text = [_textView.text stringByAppendingString:[dic1 objectForKey:@"city"]];
        _textView.text = [_textView.text stringByAppendingString:@"\n"];
        _textView.text = [_textView.text stringByAppendingString:[dic1 objectForKey:@"temp1"]];
        _textView.text = [_textView.text stringByAppendingString:@"\n"];
        _textView.text = [_textView.text stringByAppendingString:[dic1 objectForKey:@"temp2"]];
        _textView.text = [_textView.text stringByAppendingString:@"\n"];
        _textView.text = [_textView.text stringByAppendingString:[dic1 objectForKey:@"weather"]];
        _textView.text = [_textView.text stringByAppendingString:@"\n"];
        _textView.text = [_textView.text stringByAppendingString:[dic1 objectForKey:@"ptime"]];
        _textView.text = [_textView.text stringByAppendingString:@"\n"];
        
    }
    if ([jsonObj isKindOfClass:[NSArray class]]) {
        //数组类型
        NSArray *arr = (NSArray *)jsonObj;
    }
}
image.png

JSON网络解析

数据解析:
要求:1.从文件读取json数据并解析,文件名称weatherinfo.json
2.从网络读取json数据并解析http://www.weather.com.cn/data/cityinfo/101010100.html
目的:掌握通过NSJSONSerialization类解析来自文件和网络的JSON数据
重点:掌握静态函数JSONObjectWithData:option:error:的使用,灵活掌握json的数据源读取技巧

3种方法从网络上获取数据:
1.通过url从网络上获取数据
2.通过NSString自带的方法从网络上获取数据
3.用一个连接从网络上读取数据

- (IBAction)button:(id)sender {
    
    
    //中国天气网提供的接口
    //1.通过url从网络上获取数据
    NSURL *url = [NSURL URLWithString:@"http://www.weather.com.cn/data/cityinfo/101010100.html"];
    //    NSData *jsonData = [NSData dataWithContentsOfURL:url];
    //2.通过NSString自带的方法从网络上获取数据
//    NSString *jsonStr = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
//    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    
    //3.用一个连接从网络上读取数据
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
    NSData *jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
    if ([jsonObj isKindOfClass:[NSDictionary class]]) {
        //字典类型
        NSDictionary *dic = (NSDictionary *)jsonObj;
        NSDictionary *dic1 = [dic objectForKey:@"weatherinfo"];
        _textView.text = [_textView.text stringByAppendingString:@"\n"];
        _textView.text = [_textView.text stringByAppendingString:[dic1 objectForKey:@"city"]];
        _textView.text = [_textView.text stringByAppendingString:@"\n"];
        _textView.text = [_textView.text stringByAppendingString:[dic1 objectForKey:@"temp1"]];
        _textView.text = [_textView.text stringByAppendingString:@"\n"];
        _textView.text = [_textView.text stringByAppendingString:[dic1 objectForKey:@"temp2"]];
        _textView.text = [_textView.text stringByAppendingString:@"\n"];
        _textView.text = [_textView.text stringByAppendingString:[dic1 objectForKey:@"weather"]];
        _textView.text = [_textView.text stringByAppendingString:@"\n"];
        _textView.text = [_textView.text stringByAppendingString:[dic1 objectForKey:@"ptime"]];
        _textView.text = [_textView.text stringByAppendingString:@"\n"];
        
    }
    if ([jsonObj isKindOfClass:[NSArray class]]) {
        //数组类型
        NSArray *arr = (NSArray *)jsonObj;
    }
}
image.png
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,440评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,814评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,427评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,710评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,625评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,014评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,511评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,162评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,311评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,262评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,278评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,989评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,583评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,664评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,904评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,274评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,856评论 2 339

推荐阅读更多精彩内容