1.前提:添加JSONKit.h的类
2.项目中有一个Students.txt文件,且文件的内容是
这种格式的
3.接下来就看代码了
A.把json字符串转换成OC数据类型--------->这个是Foundation中NSJSONSerialization类中的方法实现的
- 拿到文件在项目中的路径
NSString * filePath = [[NSBundle mainBundle] pathForResource:@"Students" ofType:@"txt"];
- 通过文件路径,读取二进制数据
NSData * jsonData = [NSData dataWithContentsOfFile:filePath];
- 把二进制数据,转化成OC数据类型
//用来捕获错误的发生 NSError * error = nil; //把JSON字符串解析成OC的数据类型(数组或字典) NSArray * array = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
B.先把OC数据类型转化成json data, 再转化为json字符串
- 创建OC数据类型--------->这个是Foundation中NSJSONSerialization类中的方法实现的
NSDictionary * userInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:@"zhangsan",@"account",@123456,@"password",@YES,@"isNewUser", nil];
- 把OC数据类型转化为json data
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:userInfoDic options:0 error:nil];
- 把json data数据转化为json字符串
NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
C.拿到路径,先解析成json字符串,再解析成OC数据类型--------->这个是JSONKit这个类中的方法,JSONKit封装了Foundation中NSJSONSerialization这个类
NSString * filePath = [[NSBundle mainBundle] pathForResource:@"Students" ofType:@"txt"]; NSString * jsonString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
把json 字符串解析成OC数据类型
NSArray * array = [jsonString objectFromJSONString];
D.把data解析成OC数据类型--------->这个是JSONKit这个类中的方法,JSONKit封装了Foundation中NSJSONSerialization这个类
NSString * filePath = [[NSBundle mainBundle] pathForResource:@"Students" ofType:@"txt"]; NSData * jsonData = [NSData dataWithContentsOfFile:filePath]; //NSData的类目,把data解析成oc数据类型 NSArray * array = [jsonData objectFromJSONData];
E.把OC数据类型转化为json 字符串--------->这个是JSONKit这个类中的方法,JSONKit封装了Foundation中NSJSONSerialization这个类
NSDictionary * userInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:@"zhangsan",@"account",@123456,@"password",@YES,@"isNewUser", nil]; //把oc类型转换乘json类型 字符串 NSString * jsonString = [userInfoDic JSONString]; //把oc数据类型转成JSON data NSString * jsonData = [userInfoDic JSONData];