Model--JSONModel

  • JSONModel 是一个轻量级的第三方库,可以很方便的实现 Json 解析及模型转换,它缺乏个人色彩的名字也甚合朕意。

model --> JSON/Dic/Data

Model* model = [[Model alloc] initWithString:jsonString error:nil];
model.name = @"Changed Name";

//convert to dictionary
NSDictionary* dict = [model toDictionary];

//convert to text
NSString* string = [model toJSONString];

JSON/Data/Dic --> model

//AFN的网络请求大抵如此
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
   manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:kURL
       parameters:@{}
         progress:nil
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
              //这三种方式都可以实现解析,并转model,
              //但JSONModel的源码看,其实还是用系统源生的NSJSONSerialization 和 setValueWithDictionary 实现的
              // 1.NSData 直接转 model
              RespondModel *model = [[RespondModel alloc]initWithData:responseObject error:nil];
              
              // 2.json字符串转 model
              //NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
              //RespondModel *model = [[RespondModel alloc]initWithString:str
              //                                           usingEncoding:NSUTF8StringEncoding error:nil];
              
              // 3. dic 字典转 model
              //NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject
              //                                                    options:NSJSONReadingAllowFragments error:nil];
              //RespondModel *model = [[RespondModel alloc]initWithDictionary:dic error:nil];

              NSLog(@"%@",model.result);
              NSLog(@"%@",model.data.total);
              NSLog(@"%@",((TopicModel*)model.data.list[0]).title);
              NSLog(@"%@",((TopicModel*)model.data.list[8]).isHot);
              NSLog(@"%@",((TopicModel*)model.data.list[0]).addTime);

              
          } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {              
              NSLog(@"数据请求出错");
          }];

关于Model的创建
.h文件

//有些人不建议将model 写在同一个类中,
//但除非特别复杂,写在一起会很方便数据模型修改

//必须写这个空协议 
@protocol TopicModel <NSObject>
@end


//所有模型都继承自JSONModel
@interface CounterListModel : JSONModel
@property(nonatomic,retain)NSString *comment;
//可选属性,属性值可以为空,防止服务器返回数据为空导致程序崩溃
@property(nonatomic,retain)NSString <Optional>*like;
//忽略属性,属性值不需要从服务器中获取
@property(nonatomic,retain)NSString <Ignore>*view;
@end


@interface UserInfoModel : JSONModel
@property(nonatomic,retain)NSString *uid;
@property(nonatomic,retain)NSString *uname;
@property(nonatomic,retain)NSString *icon;
@end

@interface TopicModel : JSONModel
@property(nonatomic,retain)NSString *title;
@property(nonatomic,retain)NSString *contentid;
@property(nonatomic,retain)NSString *addtime_f;
@property(nonatomic,retain)NSString *addTime;
@property(nonatomic,retain)NSString *content;
@property(nonatomic,retain)NSString *coverimg;
@property(nonatomic,retain)NSString *songid;
@property(nonatomic,assign)BOOL isRecommend;
@property(nonatomic,retain)NSNumber *isHot;

@property(nonatomic,retain)UserInfoModel *userInfoModel;
@property(nonatomic,retain)CounterListModel *counterListModel;
@end

@interface DataModel : JSONModel
@property(nonatomic,copy)NSString *total;
//JSONModel处理复杂字典的原理是通过协议
//根据协议名去找到名字一样的类名去装这个模型
@property(nonatomic,retain)NSArray <TopicModel> *list;
@end

@interface RespondModel : JSONModel
@property(nonatomic,retain)NSString *result;
@property(nonatomic,retain)DataModel *data;
@end

/**
 *  [model toDictionary];  model 可以方便转字典
 *  [model toJSONString];  model 也可方便转字符串
 */

.m 有特殊需求可以写相应方法

/**
 *  The JSONMOdel framework is ARC only, you can enable ARC on per file basis.
 *   ARC only
 *   ARC only
 *   ARC only
 */

@implementation CounterListModel
+(BOOL)propertyIsOptional:(NSString *)propertyName{
    //设置属性值可以为空,防止由于服务器数据返回为空导致JSONModel异常,程序崩溃
    return YES;
}
@end

@implementation UserInfoModel
+(BOOL)propertyIsOptional:(NSString *)propertyName{
    return YES;
}
@end


@implementation RespondModel
+(BOOL)propertyIsOptional:(NSString *)propertyName{
    return YES;
}
@end


@implementation DataModel
+(BOOL)propertyIsOptional:(NSString *)propertyName{
    return YES;
}
@end


@implementation TopicModel
//属性和字典键映射
+ (JSONKeyMapper*)keyMapper{
    return [[JSONKeyMapper alloc]initWithDictionary:
  @{
      @"ishot":@"isHot",
      @"addtime":@"addTime"
                                                      
        }];
}
+(BOOL)propertyIsOptional:(NSString *)propertyName{
    
    return YES;
}

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

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,198评论 4 61
  • MVVM模式与团队合作 说到架构设计和团队协作,这个对App的开发还是比较重要的。即使作为一个专业的搬砖者,前提是...
    GitHubPorter阅读 6,694评论 9 19
  • 附加 模型 模型 网址: http://s.budejie.com/topic/list/jingxuan/1/b...
    plantAtree_dAp阅读 496评论 0 0
  • 本次活动,我的目标是什么? 让大家了解什么是拆书,能用简单的RIA便签学习法,拆小黄书 将拆书引导和运营结合,做一...
    安凌心_anne阅读 728评论 0 3
  • 气质之于女生,恬静如水,淡淡的妆容使人如沐春风;气质之于女人,一身职业装,干练的外形,走路带风,人人为之侧目。 气...
    蜗牛up666阅读 282评论 0 0