在使用kakajson过程中。遇到了将模型转换成字符串的操作。结果kakajson将模型中的字符串属性转换为了字典类型。
//模型
class JifenModel: NSObject,Convertible {
required override init() {
super.init()
self.seetime = NSDate.currentDateDayString()
}
// 用户id
var userId: String = ""
// 记录观看当天的时间
var seetime: String = ""
var videoTime: Int = 0
var infomationTime: Int = 0
var videFinsihed: Bool = false
var infomationFinished: Bool = false
}
转换用的方法
model2.userId = UserInfoManager.getUid() ?? ""
let dictStr = model2.kj.JSONString()
print(dictStr)
通过不断深挖。发现代码流程,
//先通过kj_JSONObject()方法将模型转为字典
for property in properties {
// value filter
guard let value = kj_JSONValue(
from: property.get(from: ptr)~!,
property)~! else { continue }
guard let v = Values.JSONValue(value) else { continue }
// key filter
json[mt.JSONKey(from: property.name,
kj_JSONKey(from: property))] = v
}
通过以上方法对模型所有的属性进行取值。并添加到一个字典中。
通过Values.JSONValue(value)方法进行类型判断。在类型判断中因为工程代码中做了一个对String扩展导致了现在的问题。
extension String: Convertible{}
static func JSONValue(_ value: Any?) -> Any? {
guard let v = value.kj_value else { return nil }
if v is NSNull { return nil }
switch v {
case let num as NumberValue: return _JSONValue(from: num)
//走到这个代码后,导致了因为String遵守了Convertible协议。而返回一个空{}
case let model as Convertible: return model.kj_JSONObject()
case let array as [Any]: return _JSONValue(from: array)
case let date as Date: return date.timeIntervalSince1970
case let dict as [String: Any]: return _JSONValue(from: dict)
case let url as URL: return url.absoluteString
case let set as SetValue: return _JSONValue(from: set)
case let `enum` as ConvertibleEnum: return JSONValue(`enum`.kj_value)
default: return v as? NSCoding
}
}
网友评论