当前位置: 移动技术网 > 移动技术>移动开发>IOS > 谈谈iOS开发之JSON格式数据的生成与解析

谈谈iOS开发之JSON格式数据的生成与解析

2019年07月24日  | 移动技术网移动技术  | 我要评论

本文将从四个方面对ios开发中json格式数据的生成与解析进行讲解:

一、json是什么?

二、我们为什么要用json格式的数据?

三、如何生成json格式的数据?

四、如何解析json格式的数据?

json格式取代了xml给网络传输带来了很大的便利,但是却没有了xml的一目了然,尤其是json数据很长的时候,我们会陷入繁琐复杂的数据节点查找中。这时我们就需要一款在线校验工具 bejson。

一、json是什么?

json(javascript object notation) 是一种轻量级的数据交换格式。它基于ecmascript的一个子集。 json采用完全独立于语言的文本格式,但是也使用了类似于c语言家族的习惯(包括c、c++、c#、java、javascript、perl、 python等)。这些特性使json成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成(一般用于提升网络传输速率)。

json数据主要有两种数据结构,一种是键/值,另一种是数组的形式来表示。

1、json 数据的书写格式是:名称/值对。如:

{"firstname":"brett","lastname":"mclaughlin","email":"aaaa"} 

2、json 数据的书写格式是:数组格式,当需要表示一组值时,json 不但能够提高可读性,而且可以减少复杂性。如:

{
  "programmers": [{
    "firstname": "brett",
    "lastname": "mclaughlin",
    "email": "aaaa"
  }, {
    "firstname": "elliotte",
    "lastname": "harold",
    "email": "cccc"
  }],
  "authors": [{
    "firstname": "isaac",
    "lastname": "asimov",
    "genre": "sciencefiction"
  }, {
    "firstname": "frank",
    "lastname": "peretti",
    "genre": "christianfiction"
  }],
  "musicians": [{
    "firstname": "eric",
    "lastname": "clapton",
    "instrument": "guitar"
  }, {
    "firstname": "sergei",
    "lastname": "rachmaninoff",
    "instrument": "piano"
  }]
}

二、我们为什么要用json格式的数据?

json 可以将 javascript 对象中表示的一组数据转换为字符串,然后就可以在函数之间轻松地传递这个字符串,或者在异步应用程序中将字符串从 web 客户机传递给服务器端程序。这个字符串看起来有点儿古怪,但是javascript很容易解释它,而且 json 可以表示比"名称 / 值对"更复杂的结构。例如,可以表示数组和复杂的对象,而不仅仅是键和值的简单列表。

json作为数据包格式传输的时候具有更高的效率,这是因为json不像xml那样需要有严格的闭合标签,这就让有效数据量与总数据包比大大提升,从而减少同等数据流量的情况下,网络的传输压力。

三、如何生成json格式的数据?

1、利用字典nsdictionary转换为键/值格式的数据。

// 如果数组或者字典中存储了 nsstring, nsnumber, nsarray, nsdictionary, or nsnull 之外的其他对象,就不能直接保存成文件了.也不能序列化成 json 数据.
  nsdictionary *dict = @{@"name" : @"me", @"do" : @"something", @"with" : @"her", @"address" : @"home"};
  
  // 1.判断当前对象是否能够转换成json数据.
  // yes if obj can be converted to json data, otherwise no
  bool isyes = [nsjsonserialization isvalidjsonobject:dict];
  
  if (isyes) {
    nslog(@"可以转换");
    
    /* json data for obj, or nil if an internal error occurs. the resulting data is a encoded in utf-8.
     */
    nsdata *jsondata = [nsjsonserialization datawithjsonobject:dict options:0 error:null];
    
    /*
     writes the bytes in the receiver to the file specified by a given path.
     yes if the operation succeeds, otherwise no
     */
    // 将json数据写成文件
    // 文件添加后缀名: 告诉别人当前文件的类型.
    // 注意: afn是通过文件类型来确定数据类型的!如果不添加类型,有可能识别不了! 自己最好添加文件类型.
    [jsondata writetofile:@"/users/sunnyboy/sites/json_xml/dict.json" atomically:yes];
    
    nslog(@"%@", [[nsstring alloc] initwithdata:jsondata encoding:nsutf8stringencoding]);
    
  } else {
    
    nslog(@"json数据生成失败,请检查数据格式");
    
  }

2、通过json序列化可以转换数组,但转换结果不是标准化的json格式。

   nsarray *array = @[@"qn", @18, @"ya", @"wj"];
  
  bool isyes = [nsjsonserialization isvalidjsonobject:array];
  
  if (isyes) {
    nslog(@"可以转换");
    
    nsdata *data = [nsjsonserialization datawithjsonobject:array options:0 error:null];
    
    [data writetofile:@"/users/sunnyboy/sites/json_xml/base" atomically:yes];
  
  } else {
    
    nslog(@"json数据生成失败,请检查数据格式");
    
  }

四、如何解析json格式的数据?

1、使用touchjson解析方法:(需导入包:#import "touchjson/json/cjsondeserializer.h")

//使用touchjson来解析北京的天气
//获取api接口
nsurl *url = [nsurl urlwithstring:@"http://m.weather.com.cn/data/101010100.html"];

//定义一个nserror对象,用于捕获错误信息
nserror *error;
nsstring *jsonstring = [nsstring stringwithcontentsofurl:url encoding:nsutf8stringencoding error:&error];

nslog(@"jsonstring--->%@",jsonstring);

//将解析得到的内容存放字典中,编码格式为utf8,防止取值的时候发生乱码
nsdictionary *rootdic = [[cjsondeserializer deserializer] deserialize:[jsonstring datausingencoding:nsutf8stringencoding] error:&error];

//因为返回的json文件有两层,去第二层内容放到字典中去
nsdictionary *weatherinfo = [rootdic objectforkey:@"weatherinfo"];
nslog(@"weatherinfo--->%@",weatherinfo);

//取值打印
nslog(@"%@",[nsstring stringwithformat:@"今天是 %@ %@ %@ 的天气状况是:%@ %@ ",[weatherinfo objectforkey:@"date_y"],[weatherinfo objectforkey:@"week"],[weatherinfo objectforkey:@"city"], [weatherinfo objectforkey:@"weather1"], [weatherinfo objectforkey:@"temp1"]]);

 2、使用sbjson解析方法:(需导入包:#import "sbjson/sbjson.h")

//使用sbjson解析北京的天气
nsurl *url = [nsurl urlwithstring:@"http://www.weather.com.cn/adat/sk/101010100.html"];

nserror *error = nil;

nsstring *jsonstring = [nsstring stringwithcontentsofurl:url encoding:nsutf8stringencoding error:&error];

sbjsonparser *parser = [[sbjsonparser alloc] init];

nsdictionary *rootdic = [parser objectwithstring:jsonstring error:&error];

nsdictionary *weatherinfo = [rootdic objectforkey:@"weatherinfo"];

nslog(@"%@", [nsstring stringwithformat:@"今天是 %@ %@ %@ 的天气状况是:%@ %@ ",[weatherinfo objectforkey:@"date_y"],[weatherinfo objectforkey:@"week"],[weatherinfo objectforkey:@"city"], [weatherinfo objectforkey:@"weather1"], [weatherinfo objectforkey:@"temp1"]]);

3、使用ios5自带解析类nsjsonserialization方法解析:(无需导入包,ios5支持,低版本ios不支持)

// 从中国天气预报网请求数据
  nsurl *url = [ nsurl urlwithstring:@"http://www.weather.com.cn/adat/sk/101010100.html"];
  
  // 创建请求
  nsurlrequest *request = [nsurlrequest requestwithurl:url];
  
  [[[nsurlsession sharedsession] datataskwithrequest:request completionhandler:^(nsdata * _nullable data, nsurlresponse * _nullable response, nserror * _nullable error) {
    
    // 在网络完成的 block 回调中,要增加错误机制.
    // 失败机制处理: 错误的状态码!
    
    // 最简单的错误处理机制:
    if (data && !error) {
      
      // json格式转换成字典,ios5中自带解析类nsjsonserialization从response中解析出数据放到字典中
      id obj = [nsjsonserialization jsonobjectwithdata:data options:0 error:null];
      
      nsdictionary *dict = obj[@"weatherinfo"];
      
      nslog(@"%@---%@", dict, dict[@"city"]);
    }
    
  }] resume];

 4、使用jsonkit的解析方法:(需导入包:#import "jsonkit/jsonkit.h")

//如果json是“单层”的,即value都是字符串、数字,可以使用objectfromjsonstring
nsstring *json1 = @"{\"a\":123, \"b\":\"abc\"}";
nslog(@"json1:%@",json1);

nsdictionary *data1 = [json1 objectfromjsonstring];
nslog(@"json1.a:%@",[data1 objectforkey:@"a"]);
nslog(@"json1.b:%@",[data1 objectforkey:@"b"]);

//如果json有嵌套,即value里有array、object,如果再使用objectfromjsonstring,程序可能会报错(测试结果表明:使用由网络或得到的php/json_encode生成的json时会报错,但使用nsstring定义的json字符串时,解析成功),最好使用objectfromjsonstringwithparseoptions:
nsstring *json2 = @"{\"a\":123, \"b\":\"abc\", \"c\":[456, \"hello\"], \"d\":{\"name\":\"张三\", \"age\":\"32\"}}";
nslog(@"json2:%@", json2);

nsdictionary *data2 = [json2 objectfromjsonstringwithparseoptions:jkparseoptionlooseunicode];
nslog(@"json2.c:%@", [data2 objectforkey:@"c"]);
nslog(@"json2.d:%@", [data2 objectforkey:@"d"]);

友好提示:

4中解析方式的对比:

系统的api的解析速度最快。

sbjson的解析速度为倒数第二差。

与系统api较为接近的是jsonkit。

在今后的开发过程中,建议选用系统的api或jsonkit来对json数据进行解析。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网