设为首页 加入收藏

TOP

iOS 网络编程:JSON解析(二)
2017-10-13 10:33:13 】 浏览:5193
Tags:iOS 网络编程 JSON 解析
 *jsonData = [[NSData alloc] initWithContentsOfFile:path];
 8     id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options: 0 error:nil];
 9     
10     NSInteger id = [jsonObj objectForKey: @" ResultCode "];
11     NSLog( @" %@ ",[jsonObj objectForKey: @" ResultCode "]);
12     
13     NSData *data = [NSJSONSerialization dataWithJSONObject:jsonObj options:nil error:nil];
14     [data writeToFile: @" /Users/tengfei/Desktop/s.json " atomically: true];   
15 }

 

2.2.2 以Stream为中介

      与NSData转换中介不同,通过Stream转换它是通过两种不同的对象进行。当进行JSON文件解析时,是通过NSInputStream;而当进行编码时,是通过NSOutputStream进行

 

 

 

如下表是两种Stream的创建方法:

类名

创建Stream方法

NSInputStream

+ (instancetype)inputStreamWithData:(NSData *)data

+ (instancetype)inputStreamWithFileAtPath:(NSString *)path

+ (instancetype)inputStreamWithURL:(NSURL *)url

- (instancetype)initWithData:(NSData *)data

- (instancetype)initWithFileAtPath:(NSString *)path

- (instancetype)initWithURL:(NSURL *)url

NSOutputStream

+ (instancetype)outputStreamToMemory

+ (instancetype)outputStreamToFileAtPath:(NSString *)path append:(BOOL)shouldAppend

+ (instancetype)outputStreamWithURL:(NSURL *)url append:(BOOL)shouldAppend

- (instancetype)initToMemory

- (instancetype)initToFileAtPath:(NSString *)path append:(BOOL)shouldAppend

- (instancetype)initWithURL:(NSURL *)url append:(BOOL)shouldAppend

 

如下是通过Stream进行JSON文件的编码和解码的简单示例:

 1 -( void) testJsonWithStream
 2 {
 3     NSString *path = [[NSBundle mainBundle] pathForResource: @" Notes " ofType: @" json "];  // 获取文件的NSString路径
 4      
 5     NSInputStream *inputStream = [[NSInputStream alloc] initWithFileAtPath:path];  // 创建Stream对象
 6      [inputStream open];  // 打开Stream对象
 7      
 8     id jsonObj = [NSJSONSerialization JSONObjectWithStream:inputStream options:NSJSONReadingMutableLeaves error:nil];
 9     
10     NSInteger id = [jsonObj objectForKey: @" ResultCode "];
11     NSLog( @" %@ ",[jsonObj objectForKey: @" ResultCode "]);
12     
13      // 创建输出流
14      NSOutputStream *outpuStream =&nb
首页 上一页 1 2 3 下一页 尾页 2/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇【IOS】将字体大小不同的文字底部.. 下一篇所谓的iOS中的通讯录(一)(自制..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目