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];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • iOS网络架构讨论梳理整理中。。。 其实如果没有APIManager这一层是没法使用delegate的,毕竟多个单...
    yhtang阅读 5,300评论 1 23
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,107评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,011评论 25 709
  • 这是一个物质飞速发展的时代,无数东西被制造出来,又轻易地被抛弃;这是一个娱乐至死的时代,香港岛上一闪一闪亮晶...
    污小姐阅读 1,038评论 3 7
  • 2016年07月06日 乡村夏夜 夜色凉如水,虫轻吟似梦。卸下了所有的风尘,我坐在后院,风吹过我的脚,我把拖鞋放到...
    重获自由阅读 207评论 0 1