您的位置:首页 > 移动开发 > Swift

Swift - 不借助第三方库转模型

2016-07-06 15:02 351 查看

JSON -> Model、Dictionary -> Model

文中网络用Alamofire,JSON解析用SwiftyJSON,

生成Model文件借助 JSONExport。

后面也有自己写的一个工具类,可以生成自己想要的Model,如:加上前缀

模型类:( JSON -> Model )

import Foundation
import  SwiftyJSON
struct TestModel{
///
var my_detail = ""  //字面量语法声明,设置默认值,这样避免=nil的情况
///
var my_discount = 0
///
var my_etime : String!
///
var my_expressPrice : Int!
///
var my_expressType : String!
///
var newPrice : Double!
///
var my_thumbnailUrls : [ThumbnailUrl]!

init(){}
/**
* Instantiate the instance using the passed json values to set the properties values
*/
init(fromJson json: JSON!){
if json == nil{
return
}
my_detail = json["detail"].stringValue
my_discount = json["discount"].intValue
my_etime = json["etime"].stringValue
my_expressPrice = json["expressPrice"].intValue
my_expressType = json["expressType"].stringValue
my_newPrice = json["newPrice"].floatValue
my_thumbnailUrls = [ThumbnailUrl]()
let thumbnailUrlsArray = json["thumbnailUrls"].arrayValue
for thumbnailUrlsJson in thumbnailUrlsArray{
let value = ThumbnailUrl(fromJson: thumbnailUrlsJson)
thumbnailUrls.append(value)
}

}

}


import Foundation

class ThumbnailUrl{

var my_url : String!

init(){}
/**
* Instantiate the instance using the passed json values to set the properties values
*/
init(fromJson json: JSON!){
if json == nil{
return
}
my_url = json["url"].stringValue
}

}


JSONExport工具



模型类:( 字典 -> Model )

self.dataDict.my_itemName


//转模型:
for item in dicts {
datas.append(Model.init(dict: item))
}


import Foundation
struct Model {

///
var my_price = 0.0
///
var my_itemSummary = ""
///
var my_period = 0
///
var my_thumbnailUrls = [ImageUrlModel]()

init() {}

init(dict:[String:AnyObject]) {
//因为给属性设置了前缀,所以并不能使用这一方法自动匹配,需要手动书写
//setValuesForKeysWithDictionary(dict)
my_price = dict["price"] as? Double ?? 0.0
my_itemSummary = dict["itemSummary"] as? String ?? ""
my_period = dict["period"] as? Int ?? 0
//字典中还有数组,直接转模型
if let imageDict = dict["thumbnailUrls"] as? [[String:String]] {
for item in imageDict {
my_thumbnailUrls.append(ImageUrlModel(dict: item))
}

}
//my_thumbnailUrls = dict["thumbnailUrls"] as? [[String:String]] ?? [["":""]]
}

}


工具类:

如果要一个一个属性手动敲进去,未免太麻烦了。因此写了一个工具类,只要将打印出来的复制黏贴就可以,只要在必要的地方进行修改。

现在将字典转为模型,只要

LCDModelTool.modelDefault("my", dict: dict)


struct LCDModelTool {
/*
* 没有通过第三方库 — — 字典转模型  直接将打印板中打印出来的东西黏贴到模型类里面就可以
* 适用于一般的字典结构,当字典结构比较复杂的时候只需要针对部分进行修改
* keyPrdfix : 自己想要定义的前缀
* dict : 需要转 model 的字典
* 使用 :LCDModelTool.modelDefault("my", dict: dict as! [String : AnyObject])
*/
static func modelDefault(keyPrdfix:NSString, dict:[String:AnyObject]) {
print("==========>")

for (dictKey, dictVale) in dict {

if dictVale is [AnyObject]{
print("///\nvar \(keyPrdfix)_\(dictKey) = [String]()")
}
if dictVale is [String:AnyObject]{
print("///\nvar \(keyPrdfix)_\(dictKey) = [String:AnyObject]() ")
}
if dictVale is String{
print("///\nvar \(keyPrdfix)_\(dictKey) = \"\" ")
}
if dictVale is Double{
print("///\nvar \(keyPrdfix)_\(dictKey) = 0.0 ")
}
}
print("\n");
print("init() {}")
print("\n");
print("init(dict:[String:AnyObject]) {")
for (dictKey, dictVale) in dict {
if dictVale is [AnyObject]{
print("\(keyPrdfix)_\(dictKey) = dict[\"\(dictKey)\"] as? [AnyObject] ?? []  ")
}
if dictVale is [String:AnyObject]{
print("\(keyPrdfix)_\(dictKey) = dict[\"\(dictKey)\"] as? [String:AnyObject] ?? [:]")
}
if dictVale is String{
print("\(keyPrdfix)_\(dictKey) = dict[\"\(dictKey)\"] as? String ?? \"\"  ")
}
if dictVale is Double{
print("\(keyPrdfix)_\(dictKey) = dict[\"\(dictKey)\"] as? Double ?? 0.0  ")
}
}
print("}")

print("\n==========>@end\n");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息