protocol yson{ func dicnarySerializer() -> AnyObject? func deserializer(jsonstring:String?) -> Bool func serialization() -> String? func deserialization(string:String) -> Bool func deserialization(json:JSON) -> Bool } extension yson{ func dicnarySerializer() -> 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? yson { result[label] = jsonValue.dicnarySerializer() } } return result } return self as? AnyObject } func serialization() -> String?{ let json_object = self.dicnarySerializer() let data : NSData! = try? NSJSONSerialization.dataWithJSONObject(json_object!,options: []) let str = NSString(data:data,encoding: NSUTF8StringEncoding) return str as String? } func deserialization(string:String) -> Bool{ if let json :JSON = string.fileStringToJson(){ return deserialization(json) } return false } func deserialization(json:JSON)-> Bool{ let mirror = Mirror(reflecting: self) if mirror.children.count > 0 { for case let (label?,_) in mirror.children { if(!self.deserialization(json[label])){ return false } } }else{//base type if(!self.deserializer(json.string)){ return false } } return true } func deserializer(jsonstring:String?) -> Bool{ return false } } extension Optional:yson{ func dicnarySerializer() -> AnyObject? { if let obj = self{ if let value = obj as? yson{ return value.dicnarySerializer() } } return nil } } extension NSDate :yson{ func dicnarySerializer() -> AnyObject? { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy年MM月dd日 HH:mm:ss" let str = formatter.stringFromDate(self) return str } } extension String: yson { mutating func deserializer(string:String){ self = string } } extension Int64: yson { mutating func deserializer(string:String){ if let int64 = string.toInt64(){ self = int64 } } } extension Int: yson { mutating func deserializer(string:String){ if let inttt:Int = (string as NSString).integerValue{ self = inttt } } } extension Bool: yson { mutating func deserializer(string:String){ if let inttt:Bool = (string as NSString).boolValue{ self = inttt } } } extension Dictionary: yson {} extension Array: yson { } extension Set:yson { }
还有一点东西没写完,权作笔记
参考:http://www.hangge.com/blog/cache/detail_983.html
原文链接:https://www.f2er.com/swift/323461.html