intsig171 / SmartCodable

SmartCodable is a data parsing library based on Codable. It is simple to use, with robust compatibility being one of its main features. SmartCodable 是基于Codable实现的数据解析库。简单易用,强悍的兼容性是SmartCodable的主要特点。 表层API和功能几乎和HandyJSON一致,支持快速的迁移。
https://smart-codable.vercel.app
MIT License
417 stars 43 forks source link

JSON中值和Model定义的类型不一致 解析失败(类型不兼容) #37

Closed zhangjiang1203 closed 4 months ago

zhangjiang1203 commented 4 months ago
fileprivate let jsonStr = """
{
    "username": "yuhanle",
    "age": "18",
    "weight": 65.4,
    "sex": 1,
    "location": "Toronto, Canada",
}
"""

// 模型定义
struct ZJSmartCodableModel: SmartCodable {
    var username: String?
    var age: Int?
    var weight: Double?
    var sex: Int?
    var location: String?
}

//模型解析
let people = ZJSmartCodableModel.deserialize(from: jsonStr)!

解析后错误提示

========================  [Smart Decoding Log]  ========================
ZJSmartCodableModel 👈🏻 👀
   |- age: Expected to decode Int but found a string instead.
=========================================================================

使用版本 4.0.3和4.0.4 都是一样的结果

intsig171 commented 4 months ago

image 你的数据中age是String类型,Model中是Int类型,类型不匹配。 在Codable解析框架下也是不支持解析的(系统行为)。SmartCodable做了兼容(类型转换)。 日志的意思是帮你兼容了这个问题,希望引起你的注意。 结果是正常的。

intsig171 commented 4 months ago

image