前言
ObjectMapper是一个基于Swfit语言实现JSON和Model间互转的第三方开源类库
git传送门:https://github.com/Hearst-DD/ObjectMapper
ps:经使用发现,每次都需要手动生成ObjectMapper的model进行decode JSON数据,挺麻烦的,所以就自己写了个简单的model code打印工具类👇👇
JSON model print helper
生成一个名字为ModelPrint_Z的工具类,包含了这个工具的使用步骤tip
import UIKit
//使用tip:
//1、新建一个swift文件,设置名字为SwiftModelName
//2、使用本工具类,调用 ModelPrint_Z.PrintByString(dict_str: jsonString, name: "SwiftModelName")
//3、run the project,然后打印台会打印对应的model实现方法代码
//4、copy打印的代码
//5、parse到SwiftModelName的model即可(覆盖全部model类内全部代码)
class ModelPrint_Z{
//dict_str为model的字典json string
//name为model的名称
static func PrintByString(dict_str:NSString,name:NSString){
let dict=self.dictionaryWithJosnString(jsonString: dict_str)
if (dict != nil) {
print("\n\n\n\n\nimport UIKit\nimport ObjectMapper\n")
self.Print(dict: dict!, name: name)
}else{
print("error:json数据检索失败!")
}
}
//dict为json的字典形式
//name为model的名称
static func Print(dict:NSDictionary,name:NSString){
//model code string 叠加
var var_str:String=""
var var_mapping:String=""
dict.enumerateKeysAndObjects({ (key, obj, stop) in
let key_str=key as! String
var_mapping.append("\n"+key_str+" <- map[\""+key_str+"\"]")
switch obj{
case is Int:
var_str.append("\nvar "+key_str+" : "+"Int?")
case is Double:
var_str.append("\nvar "+key_str+" : "+"Double?")
case is Bool:
var_str.append("\nvar "+key_str+" : "+"Bool?")
case is String:
var_str.append("\nvar "+key_str+" : "+"String?")
case is NSDictionary:
self.Print(dict: (obj as! NSDictionary),name: key_str as NSString)
case is NSArray:
var_str.append("\nvar "+key_str+" : "+"["+(name as String)+"List"+"]?")
let arr = obj as! NSArray
if arr.count>0{
self.Print(dict: arr[0] as! NSDictionary,name: (name as String)+"List" as NSString)
}
default:
var_str.append("\nvar "+key_str+" : "+"Any?")
}
})
var_str="class "+(name as String)+": Mappable {\n"+var_str+"\n\npublic required init?(map: Map) {\nmapping(map: map)\n}"
var_mapping="\nfunc mapping(map: Map) {"+var_mapping+"\n}\n}"
//model code str
print("\n\n\n"+var_str+"\n"+var_mapping)
}
//设置类型为静态方法
//string专成dictionaryWithJosnString
static func dictionaryWithJosnString(jsonString:NSString)->NSDictionary?{
let jsonData:Data=jsonString.data(using: String.Encoding.utf8.rawValue)!
if jsonData.isEmpty {
return nil
}else{
do {
let jsonResult = try JSONSerialization.jsonObject(with: jsonData, options:
JSONSerialization.ReadingOptions.mutableContainers)
return jsonResult as? NSDictionary
} catch {
return nil
}
}
}
}
调用model code打印
import ObjectMapper
//model数据打印助手
ModelPrint_Z.PrintByString(dict_str: JSONStr name: "AdModel")
//使用Mapper初始化model
let temperature = Mapper<AdModel>().map(JSONString: JSONStr as String)
生成的model例子,model生成是根据ObjectMapper的model规则
import UIKit
import ObjectMapper
class AdModelList: Mappable {
var relation_id : Int?
var id : Int?
var image_url : String?
var title : String?
var link_url : String?
var relation_type : Int?
var relative_url : String?
public required init?(map: Map) {
mapping(map: map)
}
func mapping(map: Map) {
relation_id <- map["relation_id"]
id <- map["id"]
image_url <- map["image_url"]
title <- map["title"]
link_url <- map["link_url"]
relation_type <- map["relation_type"]
relative_url <- map["relative_url"]
}
}
class AdModel: Mappable {
var success : Bool?
var list : [AdModelList]?
public required init?(map: Map) {
mapping(map: map)
}
func mapping(map: Map) {
success <- map["success"]
list <- map["list"]
}
}
ObjectMapper使用步骤
1、按ObjectMapper生成model
2、调用ObjectMapper的decode方法即可,如下
let temperature = Mapper<AdModel>().map(JSONString: JSONStr as String)
总结
第一次使用这种打印方式去帮助生成model,如果同学
们有更好的方式去生成model,欢迎一起交流:p
网友评论