NSJSONSerialization 自 iOS 5 起就是官方方案,效能也不差,但它有個硬性限制:只吃 Foundation 型別。最外層必須是 NSArray 或 NSDictionary,內部元素也只能是 NSString、NSNumber、NSArray、NSDictionary、NSNull。想直接把自訂的 model 丟進去,行不通。
本文示範如何藉助反射(Reflection)繞過這個限制,不依賴任何第三方庫。
// 使用者類
class User {
var name: String = "" // 姓名
var nickname: String? // 暱稱
var age: Int? // 年齡
var emails: [String]? // 郵件地址
var tels: [Telephone]? // 電話
}
// 電話結構
struct Telephone {
var title: String // 電話標題
var number: String // 號碼
}
先定義一個 JSON 協定,約定兩個方法:toJSONModel() 負責轉成可序列化的結構,toJSONString() 負責輸出字串(內部呼叫前者)。接著讓 Optional、自訂類別與基本型別都遵循這個協定。
其中 Optional 特別重寫了 toJSONModel():值為 nil 時回傳 nil,有值時才往下拆並序列化。
// 自訂 JSON 協定
protocol JSON {
func toJSONModel() -> AnyObject?
func toJSONString() -> String?
}
// 協定預設實作
extension JSON {
// 轉成可用的 JSON 模型
func toJSONModel() -> AnyObject? {
let mirror = Mirror(reflecting: self)
if mirror.children.count > 0 {
var result: [String: AnyObject] = [:]
for case let (label?, value) in mirror.children {
if let jsonValue = value as? JSON {
result[label] = jsonValue.toJSONModel()
}
}
return result
}
return self as? AnyObject
}
// 轉成 JSON 字串
func toJSONString() -> String? {
let jsonModel = self.toJSONModel()
// 交由系統的 JSON 庫轉成 NSData
let data: NSData! = try? NSJSONSerialization.dataWithJSONObject(jsonModel!, options: [])
// NSData 再轉回字串
let str = NSString(data: data, encoding: NSUTF8StringEncoding)
return str as String?
}
}
// 可選型別遵循 JSON 協定
extension Optional: JSON {
// 重寫:有值才往下轉,無值回傳 nil
func toJSONModel() -> AnyObject? {
if let x = self {
if let value = x as? JSON {
return value.toJSONModel()
}
}
return nil
}
}
// 自訂型別遵循 JSON 協定
extension User: JSON { }
extension Telephone: JSON { }
// Swift 基本型別遵循 JSON 協定
extension String: JSON { }
extension Int: JSON { }
extension Bool: JSON { }
extension Dictionary: JSON { }
extension Array: JSON { }
這裡的巧思在於 Mirror:它能讓我們在執行期取得任意物件的所有屬性名稱與值,再靠 `value as? JSON` 過濾出真正參與序列化的成員,遞迴下去就得到完整的巢狀結構。
// 建立 User 物件
let user1 = User()
user1.name = "hangge"
user1.age = 100
user1.emails = ["hangge@hangge.com", "system@hangge.com"]
let tel1 = Telephone(title: "手機", number: "123456")
let tel2 = Telephone(title: "公司座機", number: "001-0358")
user1.tels = [tel1, tel2]
// 輸出 JSON 字串
print(user1.toJSONString()!)
執行後,格式化檢視的結果如下:
{
"tels": {
"[1]": {
"number": "001-0358",
"title": "公司座機"
},
"[0]": {
"number": "123456",
"title": "手機"
}
},
"age": 100,
"name": "hangge",
"emails": {
"[1]": "system@hangge.com",
"[0]": "hangge@hangge.com"
}
}
可以注意到陣列被展開成 `"[0]"`、`"[1]"` 這類鍵名——這是反射搭配字典的必然結果,若 xuống 端要求嚴格遵循 JSON 陣列格式,這點需要另外處理。
如果專案裡本來就有 Objective-C 資源,也可以直接沿用 JSONKit:
#include "JSONKit.h"-fno-objc-arc 即可。測試程式碼:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
testJson()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func testJson() {
// Swift 字典物件
let user = [
"uname": "user1",
"tel": ["mobile": "138", "home": "010"]
]
// 轉成 JSON 字串
let jsonstring = (user as NSDictionary).JSONString()
print(jsonstring)
// 由字串反解析回字典
print(jsonstring.objectFromJSONString() as! NSDictionary)
// 轉成 NSData 型別的 JSON 數據
let jsondata = (user as NSDictionary).JSONData()
print(jsondata)
// 由 NSData 反解析回字典
print(jsondata.objectFromJSONData() as! NSDictionary)
}
}
輸出結果:
{"uname":"user1","tel":{"home":"010","mobile":"138"}}
{
tel = {
home = 010;
mobile = 138;
};
uname = user1;
}
<7b22756e 616d6522 3a227573 65723122 2c227465 6c223a7b 22686f6d 65223a22 30313022 2c226d6f 62696c65 223a2231 3338227d 7d>
{
tel = {
home = 010;
mobile = 138;
};
uname = user1;
}
兩條路各有取捨:反射方案純 Swift、可控性高,適合 model 層已在掌控之中的情況;JSONKit 則適合既有 Objective-C 程式碼的專案。