使用JSONKit将字符串,字典,数组转换成json格式

本文介绍了使用Objective-C进行JSON序列化的具体实现方法,包括如何将字符串、数组及字典等不同类型的对象转换为JSON格式,并展示了如何利用系统自带的方法进行JSON数据的编码。

原文http://blog.sina.com.cn/s/blog_6b8c3d7a01018803.html

一,引入jsonkit

    NSString *str = nil;
    //字符串
    NSMutableString *string = [[NSMutableString alloc] init];
    [string appendString:@"xxxx"];
    str = [string JSONString];
    NSLog(@"str1:%@",[NSString stringWithString:str]);
    
    
    //数组
    NSArray *array = [[NSArray alloc] initWithObjects:@"111",@"333",@"222", nil];
   // NSMutableArray *array = [NSMutableArray array];
    str = [array JSONString];
    NSLog(@"str2:%@",[NSString stringWithString:str]);
    [array release ];
    
    //字典
    NSArray *firstArr = [NSArray arrayWithObjects:@"first",@"second", nil];
    //基本数据类型转换成NSNumber类型
    NSArray *secondArr = [NSArray arrayWithObjects:[NSNumber numberWithDouble:2.1],[NSNumber numberWithBool:NO], nil];
    //加到字典中
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:firstArr,@"first",secondArr,@"second", nil];
    //转化成json格式
    str = [dic JSONString];
    NSString *str2 = [NSString stringWithString:str];
    NSLog(@"str3:%@",str2);
    
    //编码
    NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:array];
    // NSLog(@"archive:%@",archive);
    NSArray *arr2 = [NSKeyedUnarchiver unarchiveObjectWithData:archive];
    NSLog(@"arr2:%@",arr2);

 二,系统自带

// 将数组转JSON
- (NSData *)toJSONData:(id)theData{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    if ([jsonData length] > 0 && error == nil){
        return jsonData;
    }else{
        return nil;
    }
}

NSString *jsonString = [[NSString alloc] initWithData:jsonData  encoding:NSUTF8StringEncoding]; 

 

转载于:https://www.cnblogs.com/hl666/p/3703945.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值