分享

10 把从网络接口拿到的数据,转成模型。

 雪柳花明 2016-04-16
1、把数据转成模型,怎么转,模型的内容依赖与数据。 
 
 这里只举例了一个数据。下面的数据都是类似的。

返回的数据为字典类型。posts便是键,根据健可以得到响应的键值。

 NSArray *statusDictArray=resultDict[@"posts"];//根据key键值拿到返回字典的posts对应值。

对于数据模型而言:
大模型:id,  url,  title, date,tags小模型,author小模型,comment_count,custom_fields小模型。


@interface User_Model : NSObject

/*   NSNumber   用户id*/

@property(nonatomic,assign) NSNumber *ID;


/*   String 网址:"url": "http:\/\/jandan.net\/2016\/04\/16\/czech-new-name.html",*/

@property(nonatomic,copy) NSString *url;


/* String   用户的标题"title": d*/

@property(nonatomic,copy) NSString *title;


/* NSDate 用户日期:date": "2016-04-16 14:00:25",*/

@property(nonatomic,copy) NSDate *date;


/* Tags_Model标签 tags*/   // tags value 后是【  所以是NSArray

@property(nonatomic,strongNSArray<Tags_Model *> *tags;


/* Author_Model author*/

@property(nonatomic,strong) Author_Model *author;


/* NSNumber comment_conut*/

@property(nonatomic,assign) NSNumber *comment_count;


/* custom_fields thumb_c */

@property(nonatomic,copy) custom_fields *thumb_c;

对于tags小模型而言,在进行细分。


@interface Tags_Model : NSObject


@property(nonatomic,copy) NSNumber *id;


/* NSString slug */

@property(nonatomic,copy) NSString *slug;


/* NSString title */

@property(nonatomic,copy) NSString *title;


/* NSString   description */

@property(nonatomic,copy) NSString *desption;


/* NSNumber   post_count*/

@property(nonatomic,assign) NSNumber *post_count;

@end

其余的类似。
这样分割之后,数据有清晰的层次结构。方便管理,减轻数据压力。


对于拿到的数据,进行如下操作:

头文件的操作:@interface TableViewController ()

/**数据数组(存放着所有的数据)*/

@property (nonatomic, strong) NSArray *postses;

//@property(nonatomic,copy)User_Model *user;

@end

AFN拿到的数据,进行处理。

 [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, NSDictionary *resultDict) {

        NSLog(@"从接口返回的数据resultDict数据类型%@",[resultDict class]);

        

        //数据字典-----数组模型

        NSArray *statusDictArray=resultDict[@"posts"];//根据key键值拿到返回字典的posts对应的数据。

        NSLog(@"根据posts拿到的statusDictArray%@,数据类型%@",statusDictArray,[statusDictArray class]);

        

        

        self.postses = [User_Model mj_objectArrayWithKeyValuesArray:statusDictArray];

        

        NSLog(@"数据转模型%@",self.postses);

        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@"请求失败---%@", error);

    }];

这里呢,出了点问题,经过刘大神的指导之后,发现问题所在之处。对于MJExtension要用最新的,最重要的,要对这个框架很熟悉。


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多