IOS自带json解析之生成json对象


我用的Json例子如下(网络上很多人都用这个例子):
{
  "生命基金会" {
    "dabei88" {
      "digits" 22,
      "name" "大悲出相图",
      "length" 88
    }
  },
  "华藏净宗学会" {
    "zhaomu" {
      "digits" 3,
      "name" "净宗朝暮课本",
      "length" 142
    },
    "kesong" {
      "digits" 2,
      "name" "净宗共修课本",
      "length" 75
    }
  }
}
(一)首先自己写一个函数,用来生成Json,如下:
(NSDictionary *)dictionaryByCustom{
    NSMutableDictionary *mutableDict=[NSMutableDictionary dictionary];
    NSMutableDictionary *sub1Dict=[NSMutableDictionary dictionary];
    NSMutableDictionary *sub2Dict=[NSMutableDictionary dictionary];
    
    sub2Dict=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"净宗朝暮课本",@"name",[NSNumber numberWithInteger:142],@"length",[NSNumber numberWithInteger:3],@"digits",nil];
    [sub1Dict setValue:sub2Dict forKey:@"zhaomu"];
    
    sub2Dict=[NSMutableDictionary dictionary];//重新分配
    sub2Dict=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"净宗共修课本",@"name",[NSNumber numberWithInteger:75],@"length",[NSNumber numberWithInteger:2],@"digits",nil];
    [sub1Dict setValue:sub2Dict forKey:@"kesong"];
    
    [mutableDict setValue:sub1Dict forKey:@"华藏净宗学会"];
    
    sub1Dict=[NSMutableDictionary dictionary];//重新分配
    sub2Dict=[NSMutableDictionary dictionary];//重新分配
    sub2Dict=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"大悲出相图",@"name",[NSNumber numberWithInteger:88],@"length",[NSNumber numberWithInteger:22],@"digits",nil];
    [sub1Dict setValue:sub2Dict forKey:@"dabei88"];
    
    [mutableDict setValue:sub1Dict forKey:@"生命基金会"];
    
    return mutableDict;
}
(二)将Json存进本地文件夹(下面代码在你需要用到的地方写):
 //==生成Json对应的Data
    NSError *error=nil;
    NSData *JsonData=[NSJSONSerialization dataWithJSONObject:[self dictionaryByCustom] options:NSJSONWritingPrettyPrinted error:&error];
    if (error) {
        NSLog(@"Error %@",[error localizedDescription]);
    }
    //==Json文件路径
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *Json_path=[path stringByAppendingPathComponent:@"JsonFile.json"];
    //==写入文件
    NSLog(@"%@",[JsonData writeToFile:Json_path atomically:YES] ? @"Succeed":@"Failed");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值