一 簡介
二 特性
三 安裝使用以及封裝
四 使用示例
五 項(xiàng)目使用示例
一 簡介
HandyJSON
是一個用于Swift
語言中的JSON
序列化/反序列化庫。
與其他流行的Swift JSON
庫相比,HandyJSON
的特點(diǎn)是肖揣,它支持純swift
類贬墩,使用也簡單蜈膨。它反序列化時(把JSON轉(zhuǎn)換為Model)不要求Model
從NSObject
繼承(因?yàn)樗皇腔?code>KVC機(jī)制)问潭,也不要求你為Model
定義一個Mapping
函數(shù)鸠项。只要你定義好Model
類,聲明它服從HandyJSON
協(xié)議辅甥,HandyJSON
就能自行以各個屬性的屬性名為Key
酝润,從JSON
串中解析值。
HandyJSON
目前依賴于從Swift Runtime
源碼中推斷的內(nèi)存規(guī)則璃弄,任何變動我們將隨時跟進(jìn)要销。
二 特性
- 序列化
Model
到JSON、從JSON反序列化
到Model
- 自然地以
Model
的屬性名稱作為解析JSON
的Key
夏块,不需要額外指定- 支持
Swift
中大部分類型- 支持
class
疏咐、struct
定義的Model
- 支持自定義解析規(guī)則
- 類型自適應(yīng),如
JSON
中是一個Int
脐供,但對應(yīng)Model
是String
字段浑塞,會自動完成轉(zhuǎn)化
三 安裝使用以及封裝
3.1 安裝
我使用的是cocopod
進(jìn)行包引入管理,修改Prodfie
文件政己,添加如下代碼:
pod 'HandyJSON'
3.2 封裝
為了方便我們項(xiàng)目中的使用酌壕,我們一般都會在做一層封裝
,方便庫的以后升級替換
歇由,以及方便日常業(yè)務(wù)邏輯的處理
JsonUtil.swift
import UIKit
import HandyJSON
class JsonUtil: NSObject {
/**
* Json轉(zhuǎn)對象
*/
static func jsonToModel(_ jsonStr:String,_ modelType:HandyJSON.Type) ->BaseModel {
if jsonStr == "" || jsonStr.count == 0 {
#if DEBUG
print("jsonoModel:字符串為空")
#endif
return BaseModel()
}
return modelType.deserialize(from: jsonStr) as! BaseModel
}
/**
* Json轉(zhuǎn)數(shù)組對象
*/
static func jsonArrayToModel(_ jsonArrayStr:String, _ modelType:HandyJSON.Type) ->[BaseModel] {
if jsonArrayStr == "" || jsonArrayStr.count == 0 {
#if DEBUG
print("jsonToModelArray:字符串為空")
#endif
return []
}
var modelArray:[BaseModel] = []
let data = jsonArrayStr.data(using: String.Encoding.utf8)
let peoplesArray = try! JSONSerialization.jsonObject(with:data!, options: JSONSerialization.ReadingOptions()) as? [AnyObject]
for people in peoplesArray! {
modelArray.append(dictionaryToModel(people as! [String : Any], modelType))
}
return modelArray
}
/**
* 字典轉(zhuǎn)對象
*/
static func dictionaryToModel(_ dictionStr:[String:Any],_ modelType:HandyJSON.Type) -> BaseModel {
if dictionStr.count == 0 {
#if DEBUG
print("dictionaryToModel:字符串為空")
#endif
return BaseModel()
}
return modelType.deserialize(from: dictionStr) as! BaseModel
}
/**
* 對象轉(zhuǎn)JSON
*/
static func modelToJson(_ model:BaseModel?) -> String {
if model == nil {
#if DEBUG
print("modelToJson:model為空")
#endif
return ""
}
return (model?.toJSONString())!
}
/**
* 對象轉(zhuǎn)字典
*/
static func modelToDictionary(_ model:BaseModel?) -> [String:Any] {
if model == nil {
#if DEBUG
print("modelToJson:model為空")
#endif
return [:]
}
return (model?.toJSON())!
}
}
說明:這里我封裝了5個方法卵牍,Json
轉(zhuǎn)對象,Json
轉(zhuǎn)數(shù)組對象
印蓖,字典
轉(zhuǎn)對象
辽慕,對象
轉(zhuǎn)JSON
,對象
轉(zhuǎn)字典
,基本覆蓋了我們?nèi)粘i_發(fā)的常用操作赦肃,與這個工具類相對應(yīng)的溅蛉,還有一個公共的基礎(chǔ)module
類
BaseModel.swift
import UIKit
import HandyJSON
class BaseModel: HandyJSON {
// var date: Date?
// var decimal: NSDecimalNumber?
// var url: URL?
// var data: Data?
// var color: UIColor?
required init() {}
func mapping(mapper: HelpingMapper) { //自定義解析規(guī)則,日期數(shù)字顏色他宛,如果要指定解析格式船侧,子類實(shí)現(xiàn)重寫此方法即可
// mapper <<<
// date <-- CustomDateFormatTransform(formatString: "yyyy-MM-dd")
//
// mapper <<<
// decimal <-- NSDecimalNumberTransform()
//
// mapper <<<
// url <-- URLTransform(shouldEncodeURLString: false)
//
// mapper <<<
// data <-- DataTransform()
//
// mapper <<<
// color <-- HexColorTransform()
}
}
說明:封裝的基礎(chǔ)model
類。開發(fā)中厅各,我們自定義的model
繼承此model
即可省去了每次都要引入 “import HandyJSON”
镜撩,以及每次都要實(shí)現(xiàn)“required init() {}”
方法,子類如果要自定義解析規(guī)則队塘,重寫mapping
方法即可
四 使用示例
基于以上封裝的類我們實(shí)現(xiàn)幾個示例做具體說明袁梗,主要有以下幾個示例:
- Json轉(zhuǎn)模型 (常用)
- Json數(shù)組轉(zhuǎn)模型 (常用)
- 字典轉(zhuǎn)模型
- 模型轉(zhuǎn)Json
- 模型轉(zhuǎn)字典
- json與嵌套的模型相互轉(zhuǎn)換特殊類型字段轉(zhuǎn)換,日期類型憔古,數(shù)字類型遮怜,顏色
1. Json轉(zhuǎn)模型 (常用)
JsonToModel.swift
import UIKit
class JsonToModel: BaseModel {
var id :Int?
var color:String?
var name:String?
}
fileprivate func jsonTomodel(){
let jsonString = "{\"id\":12345,\"color\":\"black\",\"name\":\"cat\"}"
let model:JsonToModel = JsonUtil.jsonToModel(jsonString,JsonToModel.self) as! JsonToModel
print(model.name as Any)
print(model.color as Any)
print(model.id as Any)
}
說明:調(diào)用jsonToModel(_ jsonStr:String,_ modelType:HandyJSON.Type)
,傳入兩個參數(shù),第一個參數(shù)是要轉(zhuǎn)換的Json
字符串鸿市,第二個參數(shù)是要轉(zhuǎn)換的model
類的class
锯梁,因?yàn)楣差愔薪y(tǒng)一返回的都是BaseModel
類型即碗,所以這里要調(diào)用 as!
轉(zhuǎn)換成具體的子類類型。
2. Json數(shù)組轉(zhuǎn)模型 (常用)
JsonArrayToModel.swift
import UIKit
class JsonArrayToModel: BaseModel {
var name:String?
var id :String?
}
//json數(shù)組轉(zhuǎn)模型
fileprivate func jsonArrayTomodel() {
let jsonArrayString: String = "[{\"name\":\"Bob\",\"id\":\"1\"}, {\"name\":\"Lily\",\"id\":\"2\"}, {\"name\":\"Lucy\",\"id\":\"3\"}]"
let cats = JsonUtil.jsonArrayToModel(jsonArrayString, JsonArrayToModel.self) as! [JsonArrayToModel]
for model:JsonArrayToModel in cats {
print(model.name as Any)
}
}
說明:調(diào)用jsonArrayToModel(_ jsonArrayStr:String, _ modelType:HandyJSON.Type)
傳入兩個參數(shù)陌凳,第一個參數(shù)是要轉(zhuǎn)換的數(shù)組型Json
字符串剥懒,第二個參數(shù)是要轉(zhuǎn)換的model
類的class
,返回值是一個數(shù)組合敦,因?yàn)楣差愔薪y(tǒng)一返回的都是BaseModel
類型初橘,所以這里要調(diào)用as!
轉(zhuǎn)換成具體的子類類型數(shù)組。
3 字典轉(zhuǎn)模型
import UIKit
class JsonToModel: BaseModel {
var id :Int!
var color:String?
var name:String?
}
//字典轉(zhuǎn)模型
fileprivate func dicToModel() {
var dict = [String: Any]()
dict["id"] = 1.1
dict["color"] = "hello"
dict["name"] = "李四"
let model:JsonToModel = JsonUtil.dictionaryToModel(dict,JsonToModel.self) as! JsonToModel
print(model.name as Any)
print(model.color as Any)
print(model.id as Any)
}
說明:調(diào)用dictionaryToModel(_ dictionStr:[String:Any],_ modelType:HandyJSON.Type)
蛤肌,傳入兩個參數(shù)壁却,第一個參數(shù)是要轉(zhuǎn)換的字典對象,第二個參數(shù)是要轉(zhuǎn)換的model
類的class
裸准,因?yàn)楣差愔薪y(tǒng)一返回的都是BaseModel
類型展东,所以這里要調(diào)用as!
轉(zhuǎn)換成具體的子類類型。
4. 模型轉(zhuǎn)Json
JsonToModel.swift
import UIKit
class JsonToModel: BaseModel {
var id :Int!
var color:String?
var name:String?
}
//模型轉(zhuǎn)json
fileprivate func modelToJson() {
let model:JsonToModel = JsonToModel()
model.color = "red"
model.id = 100
model.name = "李四真"
let modelTostring = JsonUtil.modelToJson(model)
print(modelTostring)
}
說明:調(diào)用modelToJson(_ model:BaseModel?)
炒俱,傳入一個參數(shù)盐肃,傳入一個module
對象,返回值是一個JSON
字符串
5. 模型轉(zhuǎn)字典
JsonToModel.swift
import UIKit
class JsonToModel: BaseModel {
var id :Int!
var color:String?
var name:String?
}
//模型轉(zhuǎn)字典
fileprivate func modelTodiction() {
let model:JsonToModel = JsonToModel()
model.color = "red"
model.id = 100
model.name = "李四"
let modelTostring = JsonUtil.modelToDictionary(model)
print(modelTostring["name"] as Any)
}
說明:調(diào)用modelToDictionary(_ model:BaseModel?)
傳入一個參數(shù)权悟,傳入一個module
對象砸王,返回值是一個字典對象,對于日常開發(fā)中峦阁,有時候后臺只返回一個字段谦铃,比如返回一個成功信息字段,直接把返回的json
串轉(zhuǎn)換成一個字典即可榔昔,沒必要再構(gòu)建一個model
去轉(zhuǎn)換驹闰。
6. json與嵌套的模型相互轉(zhuǎn)換
CombineModel.swift
import UIKit
class Composition: BaseModel {
var aInt:Int?
var aString:String?
}
class CombineModel: BaseModel {
var aInt:Int?
var comp1:Composition?
var comp2:[Composition] = []
}
//json與嵌套的模型相互轉(zhuǎn)換
fileprivate func jsonTocombilModel() {
let model:CombineModel = CombineModel()
model.aInt = 1001
let posModel1 = Composition()
posModel1.aInt = 1
posModel1.aString = "趙六1"
let posModel2 = Composition()
posModel2.aInt = 2
posModel2.aString = "趙六2"
let posModel3 = Composition()
posModel3.aInt = 3
posModel3.aString = "趙六3"
model.comp1 = posModel1
model.comp2.append(posModel2)
model.comp2.append(posModel3)
let modeString = JsonUtil.modelToJson(model)
print(modeString)
let model2 = JsonUtil.jsonToModel(modeString, CombineModel.self)
print(model2)
}
說明:還是調(diào)用Json轉(zhuǎn)模型,模型轉(zhuǎn)Json的方法
撒会,本例子演示的是對象嵌套嘹朗,對象里面可以嵌套對象,可以嵌套對象數(shù)組诵肛,平時我們開發(fā)經(jīng)常遇到這種結(jié)構(gòu)的Json串
屹培。
7. 特殊類型字段轉(zhuǎn)換,日期類型怔檩,數(shù)字類型褪秀,顏色
SpacialTypeModel.swift
import UIKit
import HandyJSON
class SpacialTypeModel: BaseModel {
var date: Date?
var decimal: NSDecimalNumber?
var url: URL?
var data: Data?
var color: UIColor?
override func mapping(mapper: HelpingMapper) {
mapper <<<
date <-- CustomDateFormatTransform(formatString: "yyyy-MM-dd")
mapper <<<
decimal <-- NSDecimalNumberTransform()
mapper <<<
url <-- URLTransform(shouldEncodeURLString: false)
mapper <<<
data <-- DataTransform()
mapper <<<
color <-- HexColorTransform()
}
}
// 特殊類型字段轉(zhuǎn)換,日期類型薛训,數(shù)字類型溜歪,顏色
fileprivate func jsonToSpecialModel () {
let object = SpacialTypeModel()
object.date = Date()
object.decimal = NSDecimalNumber(string: "1.23423414371298437124391243")
object.url = URL(string: "https://www.aliyun.com")
object.data = Data(base64Encoded: "aGVsbG8sIHdvcmxkIQ==")
object.color = UIColor.blue
let specailModelString = JsonUtil.modelToJson(object)
print(object.toJSONString()!)
// it prints:
// {"date":"2017-09-11","decimal":"1.23423414371298437124391243","url":"https:\/\/www.aliyun.com","data":"aGVsbG8sIHdvcmxkIQ==","color":"0000FF"}
let mappedObject:SpacialTypeModel = JsonUtil.jsonToModel(specailModelString, SpacialTypeModel.self) as! SpacialTypeModel
print(mappedObject.date as Any)
}
說明:本例演示的是對于對象里含有特殊類型字段的轉(zhuǎn)換方法,主要注意點(diǎn)在構(gòu)建model
類里许蓖,我們要重寫父類mapping
方法還要引入HandyJSON
頭文件
五 項(xiàng)目使用示例
// MARK: - 基類模型轉(zhuǎn)模型為返回類型為[String:Any]
public struct DailyStudyBaseModel<T>:HandyJSON {
public var code: Int?
public var msg: String?
public var msgDetail: String?
public var data: T?
public init() {
}
}
// MARK: - 基類模型轉(zhuǎn)模型為返回類型為[[String:Any]]
public struct DailyStudyBaseListModel<T>:HandyJSON {
public var code: Int?
public var msg: String?
public var msgDetail: String?
public var data: [T]?
public init() {
}
}
// MARK: - 基類模型轉(zhuǎn)模型為返回類型為bool 或者是 其他的
public struct DailyStudyBaseResultModel:HandyJSON {
public var code: Int?
public var msg: String?
public var msgDetail: String?
public var data: Any?
public init() {
}
}
// MARK: - 處理分頁查詢返回的模型
public struct SDBasePageModel<T:HandyJSON>: HandyJSON {
public var pageNum: Int?
public var hasNextPage: Bool?
public var list :[T]?
public init() {
}
}
import Foundation
import SDBasicProject
let width = (SDJG_ScreenWidth - 20 - 18 - 18 - 40) / 3
class JHAdressModel: HandyJSON {
var title : String = ""
var list: [JHAdressCityModel] = []
required init() {
}
}
class JHAdressCityModel: HandyJSON {
var c_province : String = ""
var c_pinyin : String = ""
var c_code : String = ""
var selected: Bool = false
// var label : String = ""
var value : String = ""
var height: CGFloat = 0.0
required init() {
}
var label: String? {
didSet{
let liveNameHeight = self.label?.extGetHeightByWidth(with: self.label ?? "" , width: width, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: SDAuRate(value: 17), weight: .medium)])
self.height = 8 + (liveNameHeight ?? 0) + 8
}
}
}
//賦值
public var model: JHAdressCityModel? {
didSet{
nameLabel.text = model?.label ?? ""
if model?.label?.isEmpty == true{
self.layer.borderColor = UIColor.clear.cgColor
self.backgroundColor = .clear
self.isUserInteractionEnabled = false
}else{
self.isUserInteractionEnabled = true
if model?.selected == true {
nameLabel.textColor = .extColorWithHex("#E72026")
self.backgroundColor = .extColorWithHex("#FFE3E1")
self.layer.borderColor = UIColor.extColorWithHex("#E72227").cgColor
}else{
nameLabel.textColor = .extColorWithHex("#333333")
self.backgroundColor = .extColorWithHex("#F7F7F7")
self.layer.borderColor = UIColor.extColorWithHex("#F7F7F7").cgColor
}
}
}
}
//
// JHGoldMoldel.swift
// SDHuaYangFriendProject
//
// Created by JH on 2023/1/10.
//
import Foundation
import SDBasicProject
class JHGoldMoldel: HandyJSON {
var creditNum: String? //當(dāng)前金幣數(shù)量
// 列表數(shù)據(jù)
var productList: [JHGoldProductMoldel] = []
required init() {
}
}
class JHGoldProductMoldel: HandyJSON {
var productSkuId: String? //商品ID
var availableCredit: String?//可獲得金幣
var salePrice:String? //商品價(jià)格
var selected: Bool = false
required init() {
}
}
class JHGoldOrderMoldel: HandyJSON {
var orderNo: String? //商品ID
required init() {
}
}
class JHGoldDesMoldel: HandyJSON {
var amount: String?
var createTime: String?
var eventName:String?
var remark: String?
var type: String?
var totalAmount: String?
required init() {
}
}
//
// StationModel.swift
// SDPatternStationProject
//
// Created by lanlan on 2022/3/9.
//
import SDBasicProject
// MARK: - 站長列表
class StationMasterList :HandyJSON {
///小站名稱
var siteName:String = ""
///站長名稱
var masterName:String = ""
///站長頭像
var headImgUrl:String = ""
///站長主鍵
var id:Int = 0
///是否有直播標(biāo)記 0: 沒有 1:有
var liveFlag:Bool = false
///站長等級 0: 金牌站長
var level:Int = 0
///個人簡介
var personalProfile:String = ""
/// 關(guān)注數(shù)量
var attentionNum:Int = 0
/// 關(guān)注數(shù)量格式化
var formatAttentionNum:String = ""
/// 點(diǎn)贊數(shù)量
var thumbNum:Int = 0
///格式化點(diǎn)贊數(shù)量
var formatThumbNum:String = ""
///0: 未置頂 1:置頂
var stickieType:Bool = false
///0:未關(guān)注 1:已關(guān)注
var attentionType:Bool = false
//默認(rèn)選中
var isSeleted = false
required init() {
}
func didFinishMapping() {
formatAttentionNum = formatDecimals(num: attentionNum, separate: 10000)
formatThumbNum = formatDecimals(num: thumbNum, separate: 10000)
}
public func formatDecimals(num:Int,separate:Int) -> String {
if num < 10000 {
return "\(num)"
}
let intVal = num / separate
let doubleVal = num % separate
let suffixValue = doubleVal / 1000
if suffixValue == 0 {
return "\(intVal)w+"
}
return "\(intVal).\(suffixValue)w+"
}
}
struct StationMasterDetailModel :HandyJSON {
var course:StationMasterDetailCourseModel?
var groupInfo:StationMasterDetailGroupInfoModel?
//站長信息 本地帶的
var siteInfo:StationMasterList?
//關(guān)注人數(shù)
var memberNum:Int = 0
///關(guān)注狀態(tài)
var attentionType:Bool = false
}
struct StationMasterDetailGroupInfoModel :HandyJSON {
var itemImGroup:[StationMasterDetailGroupModel]?
var publicImGroup:StationMasterDetailGroupModel?
}
struct StationMasterDetailCourseModel :HandyJSON {
var courseFlag:Int = 0
var courseId:String = ""
var coverPic:String = ""
var headImgUrl:String = ""
var lecturerName:String = ""
var liveId:Int = 0
var liveName:String = ""
var liveStartTime:Int = 0
var liveStatus:Int = 0
var siteId:Int = 0
var skuId:Int = 0
var skuName:String = ""
var videoType:Int = 0
}
struct StationMasterDetailGroupModel :HandyJSON {
var imGroupId:String = ""
var imGroupName:String = ""
//0:加鎖 1:解鎖
var lockStatus:Int = 0
///商城需要的id
var productSpuId:Int = 0
var productSkuId:Int = 0
var siteId:String = ""
var subBrandId:String = ""
var distributeSubBrandId:String = ""
}