json parser 数据转化

本文详细介绍了如何在iOS项目中解析JSON字符串和文件,包括将JSON字符串转换为OC数据类型,将OC数据类型转化为JSON字符串,使用JSONKit类进行JSON文件的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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];


       

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值