博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【iOS】在Swift中使用JSONModel
阅读量:6978 次
发布时间:2019-06-27

本文共 2875 字,大约阅读时间需要 9 分钟。

这里不讨论JSONModel和Alamofire这两个项目,直接上代码

BaseModel.h

#import 
"
JSONModel.h
"
@interface BaseModel : JSONModel
-(instancetype)initWithDictionary:(NSDictionary*)dict;
@end

BaseModel.m 

#import 
"
BaseModel.h
"
@implementation BaseModel
//
Make all model properties optional (avoid if possible)
+(BOOL)propertyIsOptional:(NSString*)propertyName
{
    
return YES;
}
-(instancetype)initWithDictionary:(NSDictionary*)dict {
    
return (self = [[super init] initWithDictionary:dict error:nil]);
}
@end

所有的Model都要继承BaseModel,其他写法都一样

BaseAPI.swift

    
internal func requestModel<T: BaseModel>(method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, success: (T) -> Void, failure: (NSError?) -> Void) {
        mHttpManager.request(method, URLString , parameters: parameters, encoding: ParameterEncoding.JSON)
            .responseJSON { (request, response, data, error) 
in
                
if error == nil {
                    
if let dict = data 
as? NSDictionary {
                        
if let model = T(dictionary: dict 
as [NSObject : AnyObject]) {
                            success(model)
                            
return
                        }
                    }
                }
                failure(error)
        }
    }
    
    
internal func requestArray<T: BaseModel>(method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, success: (Array<T>) -> Void, failure: (NSError?) -> Void) {
        mHttpManager.request(method, URLString , parameters: parameters, encoding: ParameterEncoding.JSON)
            .responseJSON { (request, response, data, error) 
in
                
if error == nil {
                    
if let array = data 
as? NSArray {
                        
if let result = T.arrayOfModelsFromDictionaries(array 
as [AnyObject]).copy() 
as? Array<T>{
                            success(result)
                            
return
                        }
                    }
                }
                failure(error)
        }
    }

  代码说明

1、mHttpManager这个是Alamofire的Manager对象

2、注意服务端的返回的数据格式,这里支持Model和Array<Model>

3、注意在Swift里面NSDictionary转Model,用T(dictionary: dict as [NSObject : AnyObject]),这个T就是具体的泛型类型

4、注意在Swift里面NSArray转Model数组,用T.arrayOfModelsFromDictionaries(array as [AnyObject]).copy() as? Array<T>,注意不要用BaseModel. arrayOfModelsFromDictionaries(编译不会报错但是类型转不出来)

5、具体用法:

            
public func casts(success: (Array<CustomModel>) -> Void, failure: (NSError?) -> Void) {
                requestArray(Method.GET, URL_CASTS, parameters: nil, success: success, failure: failure)
            }
            
            
public func like(id: String, success: (CustomModel) -> Void, failure: (NSError?) -> Void) {
                requestModel(Method.PATCH, String(format: URL_CASTS_LIKE, id), parameters: nil, success: success, failure: failure)
            }

非常轻松和简单, 可以少写很多重复代码。

后期维护

2015-05-20 Alamofire兼容iOS7有点问题,设置head不管用,请参考我另外一篇文章:

2016-04-21 

错误:fatal error: NSArray element failed to match the Swift Array Element type,参考帖子

Swift 中使用不支持嵌套 JSONModel 数组

@property (strong, nonatomic) NSArray<App *> *apps;
@property (strong, nonatomic) NSArray<User *> *users;

解决办法: 

@property (strong, nonatomic) NSArray<NSDictionary *> *apps;
@property (strong, nonatomic) NSArray<NSDictionary *> *users;

         然后在 Swift 这边转一下

                   self.users = users.map{ User(dictionary: $
0 ) }
                   self.apps = apps.map{ App(dictionary: $
0 ) }

 本文转自博客园农民伯伯的博客,原文链接:,如需转载请自行联系原博主。

你可能感兴趣的文章
ASP.net:添加.net(2.0C#)FCKeditor在线编辑器步骤
查看>>
使用Mono管理Coyote Linux
查看>>
公有云环境下应用程序的自动化部署与水平扩展问题
查看>>
JAVAEclipse:could not find the main class,program will exit!
查看>>
Provisioning Services 7.8 入门系列教程之十三 使用 Boot Device Management(BDM)
查看>>
Centos 6.4下MySQL备份及还原详情介绍
查看>>
sql server 表索引碎片处理
查看>>
ASP网络编程从入门到精通 下载
查看>>
集群概述及原理笔记(1)
查看>>
主动防病毒内容篇
查看>>
无准备,不编程——计算机达人成长之路(15)连载
查看>>
服务器监控--cacti中英文版安装全解
查看>>
Nginx+Tomcat实现反向代理与动静分离
查看>>
WSUS Troubleshooting guide
查看>>
在SQL中使用CRL函数示例
查看>>
ATLAS入门篇之CascadingDropDown控件编程
查看>>
《从零开始学Swift》学习笔记(Day 47)——final关键字
查看>>
linux下磁盘镜像软件DRBD的使用
查看>>
snort源码的详细分析
查看>>
揭开Annotation的面纱
查看>>