iOS json的反序列化

今天在项目里面遇到需要像服务器回传json格式的情况 以前没有遇到过 下面是解决方法 当然 这里的方法不包含 回去的参数里面有id这种特殊的处理哈 这种方法以后再研究吧

//  JSONHelper.h
@interface JSONHelper : NSObject
+ (NSData *)toJSONData:(id)theData;
#import "JSONHelper.h"
@implementation JSONHelper

+ (NSData *)toJSONData:(id)theData {
    JSONHelper *helper = [[JSONHelper alloc]init];
    return [helper toJSONData:theData];
}
// 将字典或者数组转化为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;
    }
}
使用时在需要json反序列化的类里面引入头文件
字典的使用方法
NSDictionary *dict = @[@"1",@"2",@"3",@"4"];
NSData *json = [JSONHelper toJSONData: dict];
回传参数中
NSDictionary *params = @{@"jsonData":json};

在将data数据作为数组使用的时候 这种时候是什么时候呢 我们在使用tableview的时候 习惯将下载的数据把json数据作为model存放在数组中 当我们使用的时候 首先要从数组中遍历出需要的字典 然后再进行操作
//json格式转化

    NSMutableArray *temp = [NSMutableArray array];
    for (int i = 0; i < _touristList.count; i++) {
        AdjustTouristModel *touristModel = [_touristList objectAtIndex:i];
        NSString *price = [NSString stringWithFormat:@"%ld", (long)touristModel.price];
        NSDictionary *tempDict = @{@"tourist_id":touristModel.tourist_id,@"receive": price};
        [temp addObject:tempDict];
    }
    NSData *tourists = [JSONHelper toJSONData:temp];
    NSDictionary *param = @{@"touristsReceive":tourists};
    [_adjustPassParams setValuesForKeysWithDictionary:param];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值