NSJSONSerialization介绍:

NSJSONSerialization提供了将JSON数据转换为Foundation对象(一般都是NSDictionary和NSArray)和Foundation对象转换为JSON数据(可以通过调用isValidJSONObject来判断Foundation对象是否可以转换为JSON数据)

转换成JSON的对象必须具有如下属性:

1.顶层对象必须是NSArray或者NSDictionary

2.所有的对象必须是NSString、NSNumber、NSArray、NSDictionary、NSNull

3.所有NSDictionary的key必须是NSString类型

4.数字对象不能是非数值或无穷(NSNumber)

相关参数 介绍 :
1.  NSJSONReadingOptions

NSJSONReadingMutableContainers 创建可变的数组或字典 接收

NSJSONReadingMutableLeaves   指定在JSON对象可变字符串被创建为NSMutableString的实例

NSJSONReadingAllowFragments   指定解析器应该允许不属于的NSArray或NSDictionary中的实例顶层对象

2.  NSJSONWritingOptions

NSJSONWritingPrettyPrinted的意思是将生成的json数据格式化输出,这样可读性高,不设置则输出的json字符串就是一整行。

3. NSDictionary中的key就是json字符串中的key,object就是json字符串中的value,

转化问题:(json<---->Foundation)

1. json对象转换为Foundation数据(+(id)JSONObjectWithData: options: error:)(其中NSData不能为空)

if (data) {

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

NSLog(@"%@",dict);

}

2.Foundation对象转换为json数据(+(NSData *)dataWithJSONObject: options:error:);(其中对象不能为空)

NSDictionary *dict = @{@"1" : @"a",@"2" : @"b"};

//      NSArray *arr = @[@"1",@"2"];
     if  ([ NSJSONSerialization   isValidJSONObject :dict]) {
        NSData  *data = [ NSJSONSerialization   dataWithJSONObject :dict  options : NSJSONWritingPrettyPrinted   error : nil ];
         NSString  *json = [[ NSString   alloc ] initWithData :data  encoding : NSUTF8StringEncoding ];
          NSLog ( @"%@" ,json);
     }

发送json数据到服务器:1.是post请求    2.设置请求头   3.设置json数据为请求体

2.[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

3.NSData *requestData = [NSJSONSerialization dataWithJSONObject:dictData options:NSJSONWritingPrettyPrinted error:nil];

JSON转化的函数意思:

+ (BOOL)isValidJSONObject:(id)obj;//方法是检测Foundation对象能否合法转换为JSON对象

+ (nullable NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;//给一个数组或字典对象转化成NSData对象

+ (nullable id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;//给一个NSData对象,转化成数组或字典

+ (NSInteger)writeJSONObject:(id)obj toStream:(NSOutputStream *)stream options:(NSJSONWritingOptions)opt error:(NSError **)error;//将JSON数据写入到输出流,返回的是写入流的字节数

+ (nullable id)JSONObjectWithStream:(NSInputStream *)stream options:(NSJSONReadingOptions)opt error:(NSError **)error;//从输入流读取JSON数据

===================

json和xml的普及个人觉得是为了简化阅读难度,以及减轻网络负荷,json和xml 数据格式在格式化以后都是一种树状结构,可以树藤摸瓜的得到你想要的任何果子。

而不格式化的时候json和xml 又是一个普普通通的字符串,在网络通信的时候也只需要请求一次,而不用每次为得到木一个值而重复的请求服务器或者目标主机,

json和xml 都采用 键 - 值 的形式来存放数据。

xml 使用: <键> 值 </键>

json 使用:  "键" : "值"

苹果公司提供了一个官方的json解析库 NSJSONSerialization

NSJSONSerialization  里面包含了两个方法来通过不同数据形式来解析json数据。

1、+ ( id )JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError ** )error; //使用缓冲区数据来解析

2、+ ( id )JSONObjectWithStream:(NSInputStream *)stream options:(NSJSONReadingOptions)opt error:(NSError **)error; // 使用文件流的形式来解析json

/* Create a Foundation object from JSON data. Set the NSJSONReadingAllowFragments option if the parser should allow top-level objects that are not an NSArray or NSDictionary. Setting the NSJSONReadingMutableContainers option will make the parser generate mutable NSArrays and NSDictionaries. Setting the NSJSONReadingMutableLeaves option will make the parser generate mutable NSString objects. If an error occurs during the parse, then the error parameter will be set and the result will be nil.The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.*/
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;/* Create a JSON object from JSON data stream. The stream should be opened and configured. All other behavior of this method is the same as the JSONObjectWithData:options:error: method.*/
+ (id)JSONObjectWithStream:(NSInputStream *)stream options:(NSJSONReadingOptions)opt error:(NSError **)error;

解析json的步骤大概是,先把json字符串读取到缓冲区,然后使用NSJSONSerialization     里面的方法进行解析,根据不同json 格式可能返回的数据类型不一样,所以最好用 id 类型接。

eg:  id dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];

在得到解析后的数据时,然后就一步一步 ,一个一个 键 - 值 的去寻找你想要的咚咚。

Eg 1 : 从本地文件中读取json数据,然后读取到缓冲区。

- (void)jsonParse{//初始化文件路径。NSString* path  = [[NSBundle mainBundle] pathForResource:@"nanjing" ofType:@"txt"];//将文件内容读取到字符串中,注意编码NSUTF8StringEncoding 防止乱码,NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];//将字符串写到缓冲区。NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];//解析json数据,使用系统方法 JSONObjectWithData:  options: error:NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];//接下来一步一步解析。知道得到你想要的东西。NSArray* arrayResult =[dic objectForKey:@"results"]; NSDictionary* resultDic = [arrayResult objectAtIndex:0];NSDictionary* geometryDic = [resultDic objectForKey:@"geometry"];NSLog(@"geometryDic: %@,  resultDic:%@",geometryDic,resultDic);NSDictionary* locationDic = [geometryDic objectForKey:@"location"];NSNumber* lat = [locationDic objectForKey:@"lat"];NSNumber* lng = [locationDic objectForKey:@"lng"];NSLog(@"lat = %@, lng = %@",lat,lng);[jsonString release];}

Eg 2 :使用网络路径来解析json,

- (void)jsonParse{//初始化网络路径。NSString* path  = @"http://maps.googleapis.com/maps/api/geocode/json?address=nanjing&sensor=true";//初始化 url NSURL* url = [NSURL URLWithString:path];//将文件内容读取到字符串中,注意编码NSUTF8StringEncoding 防止乱码,NSString* jsonString = [[NSString alloc]initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];//将字符串写到缓冲区。NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];//解析json数据,使用系统方法 JSONObjectWithData:  options: error:NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];//一下为自定义解析, 自己想怎么干就怎么干NSArray* arrayResult =[dic objectForKey:@"results"]; NSDictionary* resultDic = [arrayResult objectAtIndex:0];NSDictionary* geometryDic = [resultDic objectForKey:@"geometry"];NSLog(@"geometryDic: %@,  resultDic:%@",geometryDic,resultDic);NSDictionary* locationDic = [geometryDic objectForKey:@"location"];NSNumber* lat = [locationDic objectForKey:@"lat"];NSNumber* lng = [locationDic objectForKey:@"lng"];NSLog(@"lat = %@, lng = %@",lat,lng);[jsonString release];}

Eg 3 :使用网络路径来解析json 。 使用NSURLRequest 和NSURLConnection 请求网络数据。

- (void)jsonParse{//初始化网络路径。NSString* path  = @"http://maps.googleapis.com/maps/api/geocode/json?address=nanjing&sensor=true";//初始化 url NSURL* url = [NSURL URLWithString:path];NSURLRequest* request = [NSURLRequest requestWithURL:url];//将请求到的字符串写到缓冲区。NSData* jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];//解析json数据,使用系统方法 JSONObjectWithData:  options: error:NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];//一下为自定义解析, 自己想怎么干就怎么干NSArray* arrayResult =[dic objectForKey:@"results"]; NSDictionary* resultDic = [arrayResult objectAtIndex:0];NSDictionary* geometryDic = [resultDic objectForKey:@"geometry"];NSLog(@"geometryDic: %@,  resultDic:%@",geometryDic,resultDic);NSDictionary* locationDic = [geometryDic objectForKey:@"location"];NSNumber* lat = [locationDic objectForKey:@"lat"];NSNumber* lng = [locationDic objectForKey:@"lng"];NSLog(@"lat = %@, lng = %@",lat,lng);}

iOS之苹果自带的json解析NSJSONSerialization(序列化)相关推荐

  1. iOS之网络数据下载和JSON解析

    iOS之网络数据下载和JSON解析 简介 在本文中笔者将要给大家介绍iOS中如何利用NSURLConnection从网络上下载数据, 如何解析下载下来的JSON数据格式, 以及如何显示数据和图片的异步 ...

  2. Java下利用Jackson进行JSON解析和序列化

    Java下利用Jackson进行JSON解析和序列化 转载于:https://www.cnblogs.com/jing1617/p/7009122.html

  3. C#开发笔记之19-如何用C#实现优雅的Json解析(序列化/反序列化)方案?

    本文由 比特飞 原创发布,欢迎大家踊跃转载. 转载请注明本文地址:C#开发笔记之19-如何用C#实现优雅的Json解析(序列化/反序列化)方案? | .Net中文网. C#开发笔记概述 另外可参考文章 ...

  4. 江在川上曰:js中的JSON解析和序列化

    江在川上曰:js中的JSON解析和序列化 JSON解析和序列化 JSON是javascript的一个严格的子集,利用了javacript中的一些模式来表示结构化数据.他只是一种数据格式,并非一种编程语 ...

  5. Lua JSON 解析与序列化

    Lua JSON 解析与序列化 原创文章,转载请注明出处:Lua JSON 解析与序列化 源码在最后面 接口 JSON.toString(data, space, toArray) data : an ...

  6. iOS 网络编程 (四)JSON解析

    1 JSON基础 JSON全称是JavaScript Object Notation,它是一种轻量级的数据交换格式.JSON数据格式既适合人进行读写,也适合计算机本身解析和生成.早期,JSON是Jav ...

  7. Android系统 (190)---Android:JSON 简介 amp; 解析方式 讲解(Gson、AS自带org.json、Jackson)

    Android:JSON 简介 & 解析方式 讲解(Gson.AS自带org.json.Jackson) 前言 现今最主流的数据交换格式 非 JSON莫属 今天,我将全面介绍 JSON &am ...

  8. Golang json 解析与生成

    文章目录 1.解析 json 1.1 map[string]interface{} 存储 json 1.2 struct 存储 json 1.3 []map[string]interface{} 解析 ...

  9. C++中json解析开源库收集,支持json5

    文章目录 zpl-c 库 HJSON cJSON RapidJSON (推荐) DAW JSON Link v2 JSON ,这库稳定,文档齐全.(推荐) json-c (c实现) json_dto ...

最新文章

  1. mac word维吾尔文字体_字加软件更新啦!万款字体一键激活!
  2. spring实现IOC的思路和方法
  3. assubclass_Java类class asSubclass()方法及示例
  4. 小程序 canvas 设置 字体 字号加粗
  5. WinLogon事件通知包编程
  6. c语言printf族函数,C语言中的printf族函数深入详解
  7. java异常处理 ppt_Java异常处理、多线程ppt课件
  8. 传输分析_医院智能物流传输系统运营管理和效益分析
  9. 软件工程之项目开发计划
  10. 关于地理数据收集与处理的基本工具推荐(3)--最新30m的DEM与DSM数据免费下载
  11. 【渝粤题库】陕西师范大学202291商业银行经营学作业(高起专)
  12. 是时候适配 Swift 3 了吗——专访 LINE iOS 开发工程师王巍
  13. 【安装库】WARNING: A newer version of conda exists.
  14. list_del()
  15. AI入门----深度学习的软硬件配置
  16. 生成二维码合成海报并下载
  17. WINCE TCPMP应用一:TCPMP概述
  18. Linux 那么多命令的来源
  19. 计算机操作系统第四版答案===转载
  20. Fecshop 开源B2C电商系统,php Yii2框架,支持多语言多货币

热门文章

  1. css中设置首字下沉效果,CSS如何实现首字下沉效果?
  2. MySQL 通配符过滤
  3. android permission denial starting intent,adb shell 启动应用时的权限问题
  4. python+opencv+百度智能云 人脸识别——人脸融合
  5. 智云物业v5.0.7
  6. 【TX2】TX2刷机教程(保存以防二刷)
  7. 花卉店家端隐私权政策
  8. 解决vscode中golang插件安装失败方法
  9. 百度快照劫持解决域名跳转网站服务器被黑挂马木马删除漏洞安全修复
  10. layui中form.val组件